]> git.ipfire.org Git - thirdparty/git.git/blob - http.c
Merge branch 'ks/t4205-test-describe-with-abbrev-fix'
[thirdparty/git.git] / http.c
1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
3 #include "hex.h"
4 #include "http.h"
5 #include "config.h"
6 #include "pack.h"
7 #include "sideband.h"
8 #include "run-command.h"
9 #include "url.h"
10 #include "urlmatch.h"
11 #include "credential.h"
12 #include "version.h"
13 #include "pkt-line.h"
14 #include "gettext.h"
15 #include "trace.h"
16 #include "transport.h"
17 #include "packfile.h"
18 #include "protocol.h"
19 #include "string-list.h"
20 #include "object-file.h"
21 #include "object-store-ll.h"
22
23 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
24 static int trace_curl_data = 1;
25 static int trace_curl_redact = 1;
26 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
27 int active_requests;
28 int http_is_verbose;
29 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
30
31 static int min_curl_sessions = 1;
32 static int curl_session_count;
33 static int max_requests = -1;
34 static CURLM *curlm;
35 static CURL *curl_default;
36
37 #define PREV_BUF_SIZE 4096
38
39 char curl_errorstr[CURL_ERROR_SIZE];
40
41 static int curl_ssl_verify = -1;
42 static int curl_ssl_try;
43 static const char *curl_http_version = NULL;
44 static const char *ssl_cert;
45 static const char *ssl_cert_type;
46 static const char *ssl_cipherlist;
47 static const char *ssl_version;
48 static struct {
49 const char *name;
50 long ssl_version;
51 } sslversions[] = {
52 { "sslv2", CURL_SSLVERSION_SSLv2 },
53 { "sslv3", CURL_SSLVERSION_SSLv3 },
54 { "tlsv1", CURL_SSLVERSION_TLSv1 },
55 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
56 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
57 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
58 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
59 #endif
60 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
61 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
62 #endif
63 };
64 static const char *ssl_key;
65 static const char *ssl_key_type;
66 static const char *ssl_capath;
67 static const char *curl_no_proxy;
68 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
69 static const char *ssl_pinnedkey;
70 #endif
71 static const char *ssl_cainfo;
72 static long curl_low_speed_limit = -1;
73 static long curl_low_speed_time = -1;
74 static int curl_ftp_no_epsv;
75 static const char *curl_http_proxy;
76 static const char *http_proxy_authmethod;
77
78 static const char *http_proxy_ssl_cert;
79 static const char *http_proxy_ssl_key;
80 static const char *http_proxy_ssl_ca_info;
81 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
82 static int proxy_ssl_cert_password_required;
83
84 static struct {
85 const char *name;
86 long curlauth_param;
87 } proxy_authmethods[] = {
88 { "basic", CURLAUTH_BASIC },
89 { "digest", CURLAUTH_DIGEST },
90 { "negotiate", CURLAUTH_GSSNEGOTIATE },
91 { "ntlm", CURLAUTH_NTLM },
92 { "anyauth", CURLAUTH_ANY },
93 /*
94 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
95 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
96 * here, too
97 */
98 };
99 #ifdef CURLGSSAPI_DELEGATION_FLAG
100 static const char *curl_deleg;
101 static struct {
102 const char *name;
103 long curl_deleg_param;
104 } curl_deleg_levels[] = {
105 { "none", CURLGSSAPI_DELEGATION_NONE },
106 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
107 { "always", CURLGSSAPI_DELEGATION_FLAG },
108 };
109 #endif
110
111 static struct credential proxy_auth = CREDENTIAL_INIT;
112 static const char *curl_proxyuserpwd;
113 static const char *curl_cookie_file;
114 static int curl_save_cookies;
115 struct credential http_auth = CREDENTIAL_INIT;
116 static int http_proactive_auth;
117 static const char *user_agent;
118 static int curl_empty_auth = -1;
119
120 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
121
122 static struct credential cert_auth = CREDENTIAL_INIT;
123 static int ssl_cert_password_required;
124 static unsigned long http_auth_methods = CURLAUTH_ANY;
125 static int http_auth_methods_restricted;
126 /* Modes for which empty_auth cannot actually help us. */
127 static unsigned long empty_auth_useless =
128 CURLAUTH_BASIC
129 | CURLAUTH_DIGEST_IE
130 | CURLAUTH_DIGEST;
131
132 static struct curl_slist *pragma_header;
133 static struct curl_slist *no_pragma_header;
134 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
135
136 static struct curl_slist *host_resolutions;
137
138 static struct active_request_slot *active_queue_head;
139
140 static char *cached_accept_language;
141
142 static char *http_ssl_backend;
143
144 static int http_schannel_check_revoke = 1;
145 /*
146 * With the backend being set to `schannel`, setting sslCAinfo would override
147 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
148 * by default.
149 */
150 static int http_schannel_use_ssl_cainfo;
151
152 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
153 {
154 size_t size = eltsize * nmemb;
155 struct buffer *buffer = buffer_;
156
157 if (size > buffer->buf.len - buffer->posn)
158 size = buffer->buf.len - buffer->posn;
159 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
160 buffer->posn += size;
161
162 return size / eltsize;
163 }
164
165 int seek_buffer(void *clientp, curl_off_t offset, int origin)
166 {
167 struct buffer *buffer = clientp;
168
169 if (origin != SEEK_SET)
170 BUG("seek_buffer only handles SEEK_SET");
171 if (offset < 0 || offset >= buffer->buf.len) {
172 error("curl seek would be outside of buffer");
173 return CURL_SEEKFUNC_FAIL;
174 }
175
176 buffer->posn = offset;
177 return CURL_SEEKFUNC_OK;
178 }
179
180 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
181 {
182 size_t size = eltsize * nmemb;
183 struct strbuf *buffer = buffer_;
184
185 strbuf_add(buffer, ptr, size);
186 return nmemb;
187 }
188
189 /*
190 * A folded header continuation line starts with any number of spaces or
191 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
192 * It is not a continuation line if the line starts with any other character.
193 */
194 static inline int is_hdr_continuation(const char *ptr, const size_t size)
195 {
196 return size && (*ptr == ' ' || *ptr == '\t');
197 }
198
199 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p)
200 {
201 size_t size = eltsize * nmemb;
202 struct strvec *values = &http_auth.wwwauth_headers;
203 struct strbuf buf = STRBUF_INIT;
204 const char *val;
205 size_t val_len;
206
207 /*
208 * Header lines may not come NULL-terminated from libcurl so we must
209 * limit all scans to the maximum length of the header line, or leverage
210 * strbufs for all operations.
211 *
212 * In addition, it is possible that header values can be split over
213 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
214 * but older servers may still emit them. A continuation header field
215 * value is identified as starting with a space or horizontal tab.
216 *
217 * The formal definition of a header field as given in RFC 7230 is:
218 *
219 * header-field = field-name ":" OWS field-value OWS
220 *
221 * field-name = token
222 * field-value = *( field-content / obs-fold )
223 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
224 * field-vchar = VCHAR / obs-text
225 *
226 * obs-fold = CRLF 1*( SP / HTAB )
227 * ; obsolete line folding
228 * ; see Section 3.2.4
229 */
230
231 /* Start of a new WWW-Authenticate header */
232 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
233 strbuf_add(&buf, val, val_len);
234
235 /*
236 * Strip the CRLF that should be present at the end of each
237 * field as well as any trailing or leading whitespace from the
238 * value.
239 */
240 strbuf_trim(&buf);
241
242 strvec_push(values, buf.buf);
243 http_auth.header_is_last_match = 1;
244 goto exit;
245 }
246
247 /*
248 * This line could be a continuation of the previously matched header
249 * field. If this is the case then we should append this value to the
250 * end of the previously consumed value.
251 */
252 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
253 /*
254 * Trim the CRLF and any leading or trailing from this line.
255 */
256 strbuf_add(&buf, ptr, size);
257 strbuf_trim(&buf);
258
259 /*
260 * At this point we should always have at least one existing
261 * value, even if it is empty. Do not bother appending the new
262 * value if this continuation header is itself empty.
263 */
264 if (!values->nr) {
265 BUG("should have at least one existing header value");
266 } else if (buf.len) {
267 char *prev = xstrdup(values->v[values->nr - 1]);
268
269 /* Join two non-empty values with a single space. */
270 const char *const sp = *prev ? " " : "";
271
272 strvec_pop(values);
273 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
274 free(prev);
275 }
276
277 goto exit;
278 }
279
280 /* Not a continuation of a previously matched auth header line. */
281 http_auth.header_is_last_match = 0;
282
283 /*
284 * If this is a HTTP status line and not a header field, this signals
285 * a different HTTP response. libcurl writes all the output of all
286 * response headers of all responses, including redirects.
287 * We only care about the last HTTP request response's headers so clear
288 * the existing array.
289 */
290 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
291 strvec_clear(values);
292
293 exit:
294 strbuf_release(&buf);
295 return size;
296 }
297
298 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
299 {
300 return nmemb;
301 }
302
303 static void closedown_active_slot(struct active_request_slot *slot)
304 {
305 active_requests--;
306 slot->in_use = 0;
307 }
308
309 static void finish_active_slot(struct active_request_slot *slot)
310 {
311 closedown_active_slot(slot);
312 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
313
314 if (slot->finished)
315 (*slot->finished) = 1;
316
317 /* Store slot results so they can be read after the slot is reused */
318 if (slot->results) {
319 slot->results->curl_result = slot->curl_result;
320 slot->results->http_code = slot->http_code;
321 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
322 &slot->results->auth_avail);
323
324 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
325 &slot->results->http_connectcode);
326 }
327
328 /* Run callback if appropriate */
329 if (slot->callback_func)
330 slot->callback_func(slot->callback_data);
331 }
332
333 static void xmulti_remove_handle(struct active_request_slot *slot)
334 {
335 curl_multi_remove_handle(curlm, slot->curl);
336 }
337
338 static void process_curl_messages(void)
339 {
340 int num_messages;
341 struct active_request_slot *slot;
342 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
343
344 while (curl_message != NULL) {
345 if (curl_message->msg == CURLMSG_DONE) {
346 int curl_result = curl_message->data.result;
347 slot = active_queue_head;
348 while (slot != NULL &&
349 slot->curl != curl_message->easy_handle)
350 slot = slot->next;
351 if (slot) {
352 xmulti_remove_handle(slot);
353 slot->curl_result = curl_result;
354 finish_active_slot(slot);
355 } else {
356 fprintf(stderr, "Received DONE message for unknown request!\n");
357 }
358 } else {
359 fprintf(stderr, "Unknown CURL message received: %d\n",
360 (int)curl_message->msg);
361 }
362 curl_message = curl_multi_info_read(curlm, &num_messages);
363 }
364 }
365
366 static int http_options(const char *var, const char *value,
367 const struct config_context *ctx, void *data)
368 {
369 if (!strcmp("http.version", var)) {
370 return git_config_string(&curl_http_version, var, value);
371 }
372 if (!strcmp("http.sslverify", var)) {
373 curl_ssl_verify = git_config_bool(var, value);
374 return 0;
375 }
376 if (!strcmp("http.sslcipherlist", var))
377 return git_config_string(&ssl_cipherlist, var, value);
378 if (!strcmp("http.sslversion", var))
379 return git_config_string(&ssl_version, var, value);
380 if (!strcmp("http.sslcert", var))
381 return git_config_pathname(&ssl_cert, var, value);
382 if (!strcmp("http.sslcerttype", var))
383 return git_config_string(&ssl_cert_type, var, value);
384 if (!strcmp("http.sslkey", var))
385 return git_config_pathname(&ssl_key, var, value);
386 if (!strcmp("http.sslkeytype", var))
387 return git_config_string(&ssl_key_type, var, value);
388 if (!strcmp("http.sslcapath", var))
389 return git_config_pathname(&ssl_capath, var, value);
390 if (!strcmp("http.sslcainfo", var))
391 return git_config_pathname(&ssl_cainfo, var, value);
392 if (!strcmp("http.sslcertpasswordprotected", var)) {
393 ssl_cert_password_required = git_config_bool(var, value);
394 return 0;
395 }
396 if (!strcmp("http.ssltry", var)) {
397 curl_ssl_try = git_config_bool(var, value);
398 return 0;
399 }
400 if (!strcmp("http.sslbackend", var)) {
401 free(http_ssl_backend);
402 http_ssl_backend = xstrdup_or_null(value);
403 return 0;
404 }
405
406 if (!strcmp("http.schannelcheckrevoke", var)) {
407 http_schannel_check_revoke = git_config_bool(var, value);
408 return 0;
409 }
410
411 if (!strcmp("http.schannelusesslcainfo", var)) {
412 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
413 return 0;
414 }
415
416 if (!strcmp("http.minsessions", var)) {
417 min_curl_sessions = git_config_int(var, value, ctx->kvi);
418 if (min_curl_sessions > 1)
419 min_curl_sessions = 1;
420 return 0;
421 }
422 if (!strcmp("http.maxrequests", var)) {
423 max_requests = git_config_int(var, value, ctx->kvi);
424 return 0;
425 }
426 if (!strcmp("http.lowspeedlimit", var)) {
427 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
428 return 0;
429 }
430 if (!strcmp("http.lowspeedtime", var)) {
431 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
432 return 0;
433 }
434
435 if (!strcmp("http.noepsv", var)) {
436 curl_ftp_no_epsv = git_config_bool(var, value);
437 return 0;
438 }
439 if (!strcmp("http.proxy", var))
440 return git_config_string(&curl_http_proxy, var, value);
441
442 if (!strcmp("http.proxyauthmethod", var))
443 return git_config_string(&http_proxy_authmethod, var, value);
444
445 if (!strcmp("http.proxysslcert", var))
446 return git_config_string(&http_proxy_ssl_cert, var, value);
447
448 if (!strcmp("http.proxysslkey", var))
449 return git_config_string(&http_proxy_ssl_key, var, value);
450
451 if (!strcmp("http.proxysslcainfo", var))
452 return git_config_string(&http_proxy_ssl_ca_info, var, value);
453
454 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
455 proxy_ssl_cert_password_required = git_config_bool(var, value);
456 return 0;
457 }
458
459 if (!strcmp("http.cookiefile", var))
460 return git_config_pathname(&curl_cookie_file, var, value);
461 if (!strcmp("http.savecookies", var)) {
462 curl_save_cookies = git_config_bool(var, value);
463 return 0;
464 }
465
466 if (!strcmp("http.postbuffer", var)) {
467 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
468 if (http_post_buffer < 0)
469 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
470 if (http_post_buffer < LARGE_PACKET_MAX)
471 http_post_buffer = LARGE_PACKET_MAX;
472 return 0;
473 }
474
475 if (!strcmp("http.useragent", var))
476 return git_config_string(&user_agent, var, value);
477
478 if (!strcmp("http.emptyauth", var)) {
479 if (value && !strcmp("auto", value))
480 curl_empty_auth = -1;
481 else
482 curl_empty_auth = git_config_bool(var, value);
483 return 0;
484 }
485
486 if (!strcmp("http.delegation", var)) {
487 #ifdef CURLGSSAPI_DELEGATION_FLAG
488 return git_config_string(&curl_deleg, var, value);
489 #else
490 warning(_("Delegation control is not supported with cURL < 7.22.0"));
491 return 0;
492 #endif
493 }
494
495 if (!strcmp("http.pinnedpubkey", var)) {
496 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
497 return git_config_pathname(&ssl_pinnedkey, var, value);
498 #else
499 warning(_("Public key pinning not supported with cURL < 7.39.0"));
500 return 0;
501 #endif
502 }
503
504 if (!strcmp("http.extraheader", var)) {
505 if (!value) {
506 return config_error_nonbool(var);
507 } else if (!*value) {
508 string_list_clear(&extra_http_headers, 0);
509 } else {
510 string_list_append(&extra_http_headers, value);
511 }
512 return 0;
513 }
514
515 if (!strcmp("http.curloptresolve", var)) {
516 if (!value) {
517 return config_error_nonbool(var);
518 } else if (!*value) {
519 curl_slist_free_all(host_resolutions);
520 host_resolutions = NULL;
521 } else {
522 host_resolutions = curl_slist_append(host_resolutions, value);
523 }
524 return 0;
525 }
526
527 if (!strcmp("http.followredirects", var)) {
528 if (value && !strcmp(value, "initial"))
529 http_follow_config = HTTP_FOLLOW_INITIAL;
530 else if (git_config_bool(var, value))
531 http_follow_config = HTTP_FOLLOW_ALWAYS;
532 else
533 http_follow_config = HTTP_FOLLOW_NONE;
534 return 0;
535 }
536
537 /* Fall back on the default ones */
538 return git_default_config(var, value, ctx, data);
539 }
540
541 static int curl_empty_auth_enabled(void)
542 {
543 if (curl_empty_auth >= 0)
544 return curl_empty_auth;
545
546 /*
547 * In the automatic case, kick in the empty-auth
548 * hack as long as we would potentially try some
549 * method more exotic than "Basic" or "Digest".
550 *
551 * But only do this when this is our second or
552 * subsequent request, as by then we know what
553 * methods are available.
554 */
555 if (http_auth_methods_restricted &&
556 (http_auth_methods & ~empty_auth_useless))
557 return 1;
558 return 0;
559 }
560
561 static void init_curl_http_auth(CURL *result)
562 {
563 if (!http_auth.username || !*http_auth.username) {
564 if (curl_empty_auth_enabled())
565 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
566 return;
567 }
568
569 credential_fill(&http_auth);
570
571 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
572 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
573 }
574
575 /* *var must be free-able */
576 static void var_override(const char **var, char *value)
577 {
578 if (value) {
579 free((void *)*var);
580 *var = xstrdup(value);
581 }
582 }
583
584 static void set_proxyauth_name_password(CURL *result)
585 {
586 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
587 proxy_auth.username);
588 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
589 proxy_auth.password);
590 }
591
592 static void init_curl_proxy_auth(CURL *result)
593 {
594 if (proxy_auth.username) {
595 if (!proxy_auth.password)
596 credential_fill(&proxy_auth);
597 set_proxyauth_name_password(result);
598 }
599
600 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
601
602 if (http_proxy_authmethod) {
603 int i;
604 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
605 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
606 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
607 proxy_authmethods[i].curlauth_param);
608 break;
609 }
610 }
611 if (i == ARRAY_SIZE(proxy_authmethods)) {
612 warning("unsupported proxy authentication method %s: using anyauth",
613 http_proxy_authmethod);
614 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
615 }
616 }
617 else
618 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
619 }
620
621 static int has_cert_password(void)
622 {
623 if (ssl_cert == NULL || ssl_cert_password_required != 1)
624 return 0;
625 if (!cert_auth.password) {
626 cert_auth.protocol = xstrdup("cert");
627 cert_auth.host = xstrdup("");
628 cert_auth.username = xstrdup("");
629 cert_auth.path = xstrdup(ssl_cert);
630 credential_fill(&cert_auth);
631 }
632 return 1;
633 }
634
635 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
636 static int has_proxy_cert_password(void)
637 {
638 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
639 return 0;
640 if (!proxy_cert_auth.password) {
641 proxy_cert_auth.protocol = xstrdup("cert");
642 proxy_cert_auth.host = xstrdup("");
643 proxy_cert_auth.username = xstrdup("");
644 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
645 credential_fill(&proxy_cert_auth);
646 }
647 return 1;
648 }
649 #endif
650
651 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
652 static void set_curl_keepalive(CURL *c)
653 {
654 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
655 }
656
657 #else
658 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
659 {
660 int ka = 1;
661 int rc;
662 socklen_t len = (socklen_t)sizeof(ka);
663
664 if (type != CURLSOCKTYPE_IPCXN)
665 return 0;
666
667 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
668 if (rc < 0)
669 warning_errno("unable to set SO_KEEPALIVE on socket");
670
671 return CURL_SOCKOPT_OK;
672 }
673
674 static void set_curl_keepalive(CURL *c)
675 {
676 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
677 }
678 #endif
679
680 /* Return 1 if redactions have been made, 0 otherwise. */
681 static int redact_sensitive_header(struct strbuf *header, size_t offset)
682 {
683 int ret = 0;
684 const char *sensitive_header;
685
686 if (trace_curl_redact &&
687 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
688 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
689 /* The first token is the type, which is OK to log */
690 while (isspace(*sensitive_header))
691 sensitive_header++;
692 while (*sensitive_header && !isspace(*sensitive_header))
693 sensitive_header++;
694 /* Everything else is opaque and possibly sensitive */
695 strbuf_setlen(header, sensitive_header - header->buf);
696 strbuf_addstr(header, " <redacted>");
697 ret = 1;
698 } else if (trace_curl_redact &&
699 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
700 struct strbuf redacted_header = STRBUF_INIT;
701 const char *cookie;
702
703 while (isspace(*sensitive_header))
704 sensitive_header++;
705
706 cookie = sensitive_header;
707
708 while (cookie) {
709 char *equals;
710 char *semicolon = strstr(cookie, "; ");
711 if (semicolon)
712 *semicolon = 0;
713 equals = strchrnul(cookie, '=');
714 if (!equals) {
715 /* invalid cookie, just append and continue */
716 strbuf_addstr(&redacted_header, cookie);
717 continue;
718 }
719 strbuf_add(&redacted_header, cookie, equals - cookie);
720 strbuf_addstr(&redacted_header, "=<redacted>");
721 if (semicolon) {
722 /*
723 * There are more cookies. (Or, for some
724 * reason, the input string ends in "; ".)
725 */
726 strbuf_addstr(&redacted_header, "; ");
727 cookie = semicolon + strlen("; ");
728 } else {
729 cookie = NULL;
730 }
731 }
732
733 strbuf_setlen(header, sensitive_header - header->buf);
734 strbuf_addbuf(header, &redacted_header);
735 ret = 1;
736 }
737 return ret;
738 }
739
740 /* Redact headers in info */
741 static void redact_sensitive_info_header(struct strbuf *header)
742 {
743 const char *sensitive_header;
744
745 /*
746 * curl's h2h3 prints headers in info, e.g.:
747 * h2h3 [<header-name>: <header-val>]
748 */
749 if (trace_curl_redact &&
750 (skip_iprefix(header->buf, "h2h3 [", &sensitive_header) ||
751 skip_iprefix(header->buf, "h2 [", &sensitive_header))) {
752 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
753 /* redaction ate our closing bracket */
754 strbuf_addch(header, ']');
755 }
756 }
757 }
758
759 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
760 {
761 struct strbuf out = STRBUF_INIT;
762 struct strbuf **headers, **header;
763
764 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
765 text, (long)size, (long)size);
766 trace_strbuf(&trace_curl, &out);
767 strbuf_reset(&out);
768 strbuf_add(&out, ptr, size);
769 headers = strbuf_split_max(&out, '\n', 0);
770
771 for (header = headers; *header; header++) {
772 if (hide_sensitive_header)
773 redact_sensitive_header(*header, 0);
774 strbuf_insertstr((*header), 0, text);
775 strbuf_insertstr((*header), strlen(text), ": ");
776 strbuf_rtrim((*header));
777 strbuf_addch((*header), '\n');
778 trace_strbuf(&trace_curl, (*header));
779 }
780 strbuf_list_free(headers);
781 strbuf_release(&out);
782 }
783
784 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
785 {
786 size_t i;
787 struct strbuf out = STRBUF_INIT;
788 unsigned int width = 60;
789
790 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
791 text, (long)size, (long)size);
792 trace_strbuf(&trace_curl, &out);
793
794 for (i = 0; i < size; i += width) {
795 size_t w;
796
797 strbuf_reset(&out);
798 strbuf_addf(&out, "%s: ", text);
799 for (w = 0; (w < width) && (i + w < size); w++) {
800 unsigned char ch = ptr[i + w];
801
802 strbuf_addch(&out,
803 (ch >= 0x20) && (ch < 0x80)
804 ? ch : '.');
805 }
806 strbuf_addch(&out, '\n');
807 trace_strbuf(&trace_curl, &out);
808 }
809 strbuf_release(&out);
810 }
811
812 static void curl_dump_info(char *data, size_t size)
813 {
814 struct strbuf buf = STRBUF_INIT;
815
816 strbuf_add(&buf, data, size);
817
818 redact_sensitive_info_header(&buf);
819 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
820
821 strbuf_release(&buf);
822 }
823
824 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
825 {
826 const char *text;
827 enum { NO_FILTER = 0, DO_FILTER = 1 };
828
829 switch (type) {
830 case CURLINFO_TEXT:
831 curl_dump_info(data, size);
832 break;
833 case CURLINFO_HEADER_OUT:
834 text = "=> Send header";
835 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
836 break;
837 case CURLINFO_DATA_OUT:
838 if (trace_curl_data) {
839 text = "=> Send data";
840 curl_dump_data(text, (unsigned char *)data, size);
841 }
842 break;
843 case CURLINFO_SSL_DATA_OUT:
844 if (trace_curl_data) {
845 text = "=> Send SSL data";
846 curl_dump_data(text, (unsigned char *)data, size);
847 }
848 break;
849 case CURLINFO_HEADER_IN:
850 text = "<= Recv header";
851 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
852 break;
853 case CURLINFO_DATA_IN:
854 if (trace_curl_data) {
855 text = "<= Recv data";
856 curl_dump_data(text, (unsigned char *)data, size);
857 }
858 break;
859 case CURLINFO_SSL_DATA_IN:
860 if (trace_curl_data) {
861 text = "<= Recv SSL data";
862 curl_dump_data(text, (unsigned char *)data, size);
863 }
864 break;
865
866 default: /* we ignore unknown types by default */
867 return 0;
868 }
869 return 0;
870 }
871
872 void http_trace_curl_no_data(void)
873 {
874 trace_override_envvar(&trace_curl, "1");
875 trace_curl_data = 0;
876 }
877
878 void setup_curl_trace(CURL *handle)
879 {
880 if (!trace_want(&trace_curl))
881 return;
882 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
883 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
884 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
885 }
886
887 static void proto_list_append(struct strbuf *list, const char *proto)
888 {
889 if (!list)
890 return;
891 if (list->len)
892 strbuf_addch(list, ',');
893 strbuf_addstr(list, proto);
894 }
895
896 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
897 {
898 long bits = 0;
899
900 if (is_transport_allowed("http", from_user)) {
901 bits |= CURLPROTO_HTTP;
902 proto_list_append(list, "http");
903 }
904 if (is_transport_allowed("https", from_user)) {
905 bits |= CURLPROTO_HTTPS;
906 proto_list_append(list, "https");
907 }
908 if (is_transport_allowed("ftp", from_user)) {
909 bits |= CURLPROTO_FTP;
910 proto_list_append(list, "ftp");
911 }
912 if (is_transport_allowed("ftps", from_user)) {
913 bits |= CURLPROTO_FTPS;
914 proto_list_append(list, "ftps");
915 }
916
917 return bits;
918 }
919
920 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
921 static int get_curl_http_version_opt(const char *version_string, long *opt)
922 {
923 int i;
924 static struct {
925 const char *name;
926 long opt_token;
927 } choice[] = {
928 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
929 { "HTTP/2", CURL_HTTP_VERSION_2 }
930 };
931
932 for (i = 0; i < ARRAY_SIZE(choice); i++) {
933 if (!strcmp(version_string, choice[i].name)) {
934 *opt = choice[i].opt_token;
935 return 0;
936 }
937 }
938
939 warning("unknown value given to http.version: '%s'", version_string);
940 return -1; /* not found */
941 }
942
943 #endif
944
945 static CURL *get_curl_handle(void)
946 {
947 CURL *result = curl_easy_init();
948
949 if (!result)
950 die("curl_easy_init failed");
951
952 if (!curl_ssl_verify) {
953 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
954 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
955 } else {
956 /* Verify authenticity of the peer's certificate */
957 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
958 /* The name in the cert must match whom we tried to connect */
959 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
960 }
961
962 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
963 if (curl_http_version) {
964 long opt;
965 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
966 /* Set request use http version */
967 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
968 }
969 }
970 #endif
971
972 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
973 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
974
975 #ifdef CURLGSSAPI_DELEGATION_FLAG
976 if (curl_deleg) {
977 int i;
978 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
979 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
980 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
981 curl_deleg_levels[i].curl_deleg_param);
982 break;
983 }
984 }
985 if (i == ARRAY_SIZE(curl_deleg_levels))
986 warning("Unknown delegation method '%s': using default",
987 curl_deleg);
988 }
989 #endif
990
991 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
992 !http_schannel_check_revoke) {
993 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
994 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
995 #else
996 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
997 #endif
998 }
999
1000 if (http_proactive_auth)
1001 init_curl_http_auth(result);
1002
1003 if (getenv("GIT_SSL_VERSION"))
1004 ssl_version = getenv("GIT_SSL_VERSION");
1005 if (ssl_version && *ssl_version) {
1006 int i;
1007 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1008 if (!strcmp(ssl_version, sslversions[i].name)) {
1009 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1010 sslversions[i].ssl_version);
1011 break;
1012 }
1013 }
1014 if (i == ARRAY_SIZE(sslversions))
1015 warning("unsupported ssl version %s: using default",
1016 ssl_version);
1017 }
1018
1019 if (getenv("GIT_SSL_CIPHER_LIST"))
1020 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1021 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1022 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1023 ssl_cipherlist);
1024
1025 if (ssl_cert)
1026 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1027 if (ssl_cert_type)
1028 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1029 if (has_cert_password())
1030 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1031 if (ssl_key)
1032 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1033 if (ssl_key_type)
1034 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1035 if (ssl_capath)
1036 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1037 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1038 if (ssl_pinnedkey)
1039 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1040 #endif
1041 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1042 !http_schannel_use_ssl_cainfo) {
1043 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1044 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1045 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1046 #endif
1047 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1048 if (ssl_cainfo)
1049 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1050 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1051 if (http_proxy_ssl_ca_info)
1052 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1053 #endif
1054 }
1055
1056 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1057 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1058 curl_low_speed_limit);
1059 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1060 curl_low_speed_time);
1061 }
1062
1063 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1064 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1065
1066 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1067 {
1068 struct strbuf buf = STRBUF_INIT;
1069
1070 get_curl_allowed_protocols(0, &buf);
1071 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1072 strbuf_reset(&buf);
1073
1074 get_curl_allowed_protocols(-1, &buf);
1075 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1076 strbuf_release(&buf);
1077 }
1078 #else
1079 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1080 get_curl_allowed_protocols(0, NULL));
1081 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1082 get_curl_allowed_protocols(-1, NULL));
1083 #endif
1084
1085 if (getenv("GIT_CURL_VERBOSE"))
1086 http_trace_curl_no_data();
1087 setup_curl_trace(result);
1088 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1089 trace_curl_data = 0;
1090 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1091 trace_curl_redact = 0;
1092
1093 curl_easy_setopt(result, CURLOPT_USERAGENT,
1094 user_agent ? user_agent : git_user_agent());
1095
1096 if (curl_ftp_no_epsv)
1097 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1098
1099 if (curl_ssl_try)
1100 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1101
1102 /*
1103 * CURL also examines these variables as a fallback; but we need to query
1104 * them here in order to decide whether to prompt for missing password (cf.
1105 * init_curl_proxy_auth()).
1106 *
1107 * Unlike many other common environment variables, these are historically
1108 * lowercase only. It appears that CURL did not know this and implemented
1109 * only uppercase variants, which was later corrected to take both - with
1110 * the exception of http_proxy, which is lowercase only also in CURL. As
1111 * the lowercase versions are the historical quasi-standard, they take
1112 * precedence here, as in CURL.
1113 */
1114 if (!curl_http_proxy) {
1115 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1116 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1117 var_override(&curl_http_proxy, getenv("https_proxy"));
1118 } else {
1119 var_override(&curl_http_proxy, getenv("http_proxy"));
1120 }
1121 if (!curl_http_proxy) {
1122 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1123 var_override(&curl_http_proxy, getenv("all_proxy"));
1124 }
1125 }
1126
1127 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1128 /*
1129 * Handle case with the empty http.proxy value here to keep
1130 * common code clean.
1131 * NB: empty option disables proxying at all.
1132 */
1133 curl_easy_setopt(result, CURLOPT_PROXY, "");
1134 } else if (curl_http_proxy) {
1135 if (starts_with(curl_http_proxy, "socks5h"))
1136 curl_easy_setopt(result,
1137 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1138 else if (starts_with(curl_http_proxy, "socks5"))
1139 curl_easy_setopt(result,
1140 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1141 else if (starts_with(curl_http_proxy, "socks4a"))
1142 curl_easy_setopt(result,
1143 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1144 else if (starts_with(curl_http_proxy, "socks"))
1145 curl_easy_setopt(result,
1146 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1147 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1148 else if (starts_with(curl_http_proxy, "https")) {
1149 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1150
1151 if (http_proxy_ssl_cert)
1152 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1153
1154 if (http_proxy_ssl_key)
1155 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1156
1157 if (has_proxy_cert_password())
1158 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1159 }
1160 #endif
1161 if (strstr(curl_http_proxy, "://"))
1162 credential_from_url(&proxy_auth, curl_http_proxy);
1163 else {
1164 struct strbuf url = STRBUF_INIT;
1165 strbuf_addf(&url, "http://%s", curl_http_proxy);
1166 credential_from_url(&proxy_auth, url.buf);
1167 strbuf_release(&url);
1168 }
1169
1170 if (!proxy_auth.host)
1171 die("Invalid proxy URL '%s'", curl_http_proxy);
1172
1173 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1174 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1175 var_override(&curl_no_proxy, getenv("no_proxy"));
1176 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1177 }
1178 init_curl_proxy_auth(result);
1179
1180 set_curl_keepalive(result);
1181
1182 return result;
1183 }
1184
1185 static void set_from_env(const char **var, const char *envname)
1186 {
1187 const char *val = getenv(envname);
1188 if (val)
1189 *var = val;
1190 }
1191
1192 void http_init(struct remote *remote, const char *url, int proactive_auth)
1193 {
1194 char *low_speed_limit;
1195 char *low_speed_time;
1196 char *normalized_url;
1197 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1198
1199 config.section = "http";
1200 config.key = NULL;
1201 config.collect_fn = http_options;
1202 config.cascade_fn = git_default_config;
1203 config.cb = NULL;
1204
1205 http_is_verbose = 0;
1206 normalized_url = url_normalize(url, &config.url);
1207
1208 git_config(urlmatch_config_entry, &config);
1209 free(normalized_url);
1210 string_list_clear(&config.vars, 1);
1211
1212 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1213 if (http_ssl_backend) {
1214 const curl_ssl_backend **backends;
1215 struct strbuf buf = STRBUF_INIT;
1216 int i;
1217
1218 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1219 case CURLSSLSET_UNKNOWN_BACKEND:
1220 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1221 "Supported SSL backends:"),
1222 http_ssl_backend);
1223 for (i = 0; backends[i]; i++)
1224 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1225 die("%s", buf.buf);
1226 case CURLSSLSET_NO_BACKENDS:
1227 die(_("Could not set SSL backend to '%s': "
1228 "cURL was built without SSL backends"),
1229 http_ssl_backend);
1230 case CURLSSLSET_TOO_LATE:
1231 die(_("Could not set SSL backend to '%s': already set"),
1232 http_ssl_backend);
1233 case CURLSSLSET_OK:
1234 break; /* Okay! */
1235 }
1236 }
1237 #endif
1238
1239 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1240 die("curl_global_init failed");
1241
1242 http_proactive_auth = proactive_auth;
1243
1244 if (remote && remote->http_proxy)
1245 curl_http_proxy = xstrdup(remote->http_proxy);
1246
1247 if (remote)
1248 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1249
1250 pragma_header = curl_slist_append(http_copy_default_headers(),
1251 "Pragma: no-cache");
1252 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1253 "Pragma:");
1254
1255 {
1256 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1257 if (http_max_requests)
1258 max_requests = atoi(http_max_requests);
1259 }
1260
1261 curlm = curl_multi_init();
1262 if (!curlm)
1263 die("curl_multi_init failed");
1264
1265 if (getenv("GIT_SSL_NO_VERIFY"))
1266 curl_ssl_verify = 0;
1267
1268 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1269 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1270 set_from_env(&ssl_key, "GIT_SSL_KEY");
1271 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1272 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1273 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1274
1275 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1276
1277 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1278 if (low_speed_limit)
1279 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1280 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1281 if (low_speed_time)
1282 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1283
1284 if (curl_ssl_verify == -1)
1285 curl_ssl_verify = 1;
1286
1287 curl_session_count = 0;
1288 if (max_requests < 1)
1289 max_requests = DEFAULT_MAX_REQUESTS;
1290
1291 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1292 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1293 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1294
1295 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1296 proxy_ssl_cert_password_required = 1;
1297
1298 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1299 curl_ftp_no_epsv = 1;
1300
1301 if (url) {
1302 credential_from_url(&http_auth, url);
1303 if (!ssl_cert_password_required &&
1304 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1305 starts_with(url, "https://"))
1306 ssl_cert_password_required = 1;
1307 }
1308
1309 curl_default = get_curl_handle();
1310 }
1311
1312 void http_cleanup(void)
1313 {
1314 struct active_request_slot *slot = active_queue_head;
1315
1316 while (slot != NULL) {
1317 struct active_request_slot *next = slot->next;
1318 if (slot->curl) {
1319 xmulti_remove_handle(slot);
1320 curl_easy_cleanup(slot->curl);
1321 }
1322 free(slot);
1323 slot = next;
1324 }
1325 active_queue_head = NULL;
1326
1327 curl_easy_cleanup(curl_default);
1328
1329 curl_multi_cleanup(curlm);
1330 curl_global_cleanup();
1331
1332 string_list_clear(&extra_http_headers, 0);
1333
1334 curl_slist_free_all(pragma_header);
1335 pragma_header = NULL;
1336
1337 curl_slist_free_all(no_pragma_header);
1338 no_pragma_header = NULL;
1339
1340 curl_slist_free_all(host_resolutions);
1341 host_resolutions = NULL;
1342
1343 if (curl_http_proxy) {
1344 free((void *)curl_http_proxy);
1345 curl_http_proxy = NULL;
1346 }
1347
1348 if (proxy_auth.password) {
1349 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1350 FREE_AND_NULL(proxy_auth.password);
1351 }
1352
1353 free((void *)curl_proxyuserpwd);
1354 curl_proxyuserpwd = NULL;
1355
1356 free((void *)http_proxy_authmethod);
1357 http_proxy_authmethod = NULL;
1358
1359 if (cert_auth.password) {
1360 memset(cert_auth.password, 0, strlen(cert_auth.password));
1361 FREE_AND_NULL(cert_auth.password);
1362 }
1363 ssl_cert_password_required = 0;
1364
1365 if (proxy_cert_auth.password) {
1366 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1367 FREE_AND_NULL(proxy_cert_auth.password);
1368 }
1369 proxy_ssl_cert_password_required = 0;
1370
1371 FREE_AND_NULL(cached_accept_language);
1372 }
1373
1374 struct active_request_slot *get_active_slot(void)
1375 {
1376 struct active_request_slot *slot = active_queue_head;
1377 struct active_request_slot *newslot;
1378
1379 int num_transfers;
1380
1381 /* Wait for a slot to open up if the queue is full */
1382 while (active_requests >= max_requests) {
1383 curl_multi_perform(curlm, &num_transfers);
1384 if (num_transfers < active_requests)
1385 process_curl_messages();
1386 }
1387
1388 while (slot != NULL && slot->in_use)
1389 slot = slot->next;
1390
1391 if (!slot) {
1392 newslot = xmalloc(sizeof(*newslot));
1393 newslot->curl = NULL;
1394 newslot->in_use = 0;
1395 newslot->next = NULL;
1396
1397 slot = active_queue_head;
1398 if (!slot) {
1399 active_queue_head = newslot;
1400 } else {
1401 while (slot->next != NULL)
1402 slot = slot->next;
1403 slot->next = newslot;
1404 }
1405 slot = newslot;
1406 }
1407
1408 if (!slot->curl) {
1409 slot->curl = curl_easy_duphandle(curl_default);
1410 curl_session_count++;
1411 }
1412
1413 active_requests++;
1414 slot->in_use = 1;
1415 slot->results = NULL;
1416 slot->finished = NULL;
1417 slot->callback_data = NULL;
1418 slot->callback_func = NULL;
1419 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1420 if (curl_save_cookies)
1421 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1422 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1423 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1424 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1425 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1426 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1427 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1428 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1429 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1430 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1431 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1432 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1433
1434 /*
1435 * Default following to off unless "ALWAYS" is configured; this gives
1436 * callers a sane starting point, and they can tweak for individual
1437 * HTTP_FOLLOW_* cases themselves.
1438 */
1439 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1440 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1441 else
1442 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1443
1444 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1445 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1446 if (http_auth.password || curl_empty_auth_enabled())
1447 init_curl_http_auth(slot->curl);
1448
1449 return slot;
1450 }
1451
1452 int start_active_slot(struct active_request_slot *slot)
1453 {
1454 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1455 int num_transfers;
1456
1457 if (curlm_result != CURLM_OK &&
1458 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1459 warning("curl_multi_add_handle failed: %s",
1460 curl_multi_strerror(curlm_result));
1461 active_requests--;
1462 slot->in_use = 0;
1463 return 0;
1464 }
1465
1466 /*
1467 * We know there must be something to do, since we just added
1468 * something.
1469 */
1470 curl_multi_perform(curlm, &num_transfers);
1471 return 1;
1472 }
1473
1474 struct fill_chain {
1475 void *data;
1476 int (*fill)(void *);
1477 struct fill_chain *next;
1478 };
1479
1480 static struct fill_chain *fill_cfg;
1481
1482 void add_fill_function(void *data, int (*fill)(void *))
1483 {
1484 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1485 struct fill_chain **linkp = &fill_cfg;
1486 new_fill->data = data;
1487 new_fill->fill = fill;
1488 new_fill->next = NULL;
1489 while (*linkp)
1490 linkp = &(*linkp)->next;
1491 *linkp = new_fill;
1492 }
1493
1494 void fill_active_slots(void)
1495 {
1496 struct active_request_slot *slot = active_queue_head;
1497
1498 while (active_requests < max_requests) {
1499 struct fill_chain *fill;
1500 for (fill = fill_cfg; fill; fill = fill->next)
1501 if (fill->fill(fill->data))
1502 break;
1503
1504 if (!fill)
1505 break;
1506 }
1507
1508 while (slot != NULL) {
1509 if (!slot->in_use && slot->curl != NULL
1510 && curl_session_count > min_curl_sessions) {
1511 curl_easy_cleanup(slot->curl);
1512 slot->curl = NULL;
1513 curl_session_count--;
1514 }
1515 slot = slot->next;
1516 }
1517 }
1518
1519 void step_active_slots(void)
1520 {
1521 int num_transfers;
1522 CURLMcode curlm_result;
1523
1524 do {
1525 curlm_result = curl_multi_perform(curlm, &num_transfers);
1526 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1527 if (num_transfers < active_requests) {
1528 process_curl_messages();
1529 fill_active_slots();
1530 }
1531 }
1532
1533 void run_active_slot(struct active_request_slot *slot)
1534 {
1535 fd_set readfds;
1536 fd_set writefds;
1537 fd_set excfds;
1538 int max_fd;
1539 struct timeval select_timeout;
1540 int finished = 0;
1541
1542 slot->finished = &finished;
1543 while (!finished) {
1544 step_active_slots();
1545
1546 if (slot->in_use) {
1547 long curl_timeout;
1548 curl_multi_timeout(curlm, &curl_timeout);
1549 if (curl_timeout == 0) {
1550 continue;
1551 } else if (curl_timeout == -1) {
1552 select_timeout.tv_sec = 0;
1553 select_timeout.tv_usec = 50000;
1554 } else {
1555 select_timeout.tv_sec = curl_timeout / 1000;
1556 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1557 }
1558
1559 max_fd = -1;
1560 FD_ZERO(&readfds);
1561 FD_ZERO(&writefds);
1562 FD_ZERO(&excfds);
1563 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1564
1565 /*
1566 * It can happen that curl_multi_timeout returns a pathologically
1567 * long timeout when curl_multi_fdset returns no file descriptors
1568 * to read. See commit message for more details.
1569 */
1570 if (max_fd < 0 &&
1571 (select_timeout.tv_sec > 0 ||
1572 select_timeout.tv_usec > 50000)) {
1573 select_timeout.tv_sec = 0;
1574 select_timeout.tv_usec = 50000;
1575 }
1576
1577 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1578 }
1579 }
1580
1581 /*
1582 * The value of slot->finished we set before the loop was used
1583 * to set our "finished" variable when our request completed.
1584 *
1585 * 1. The slot may not have been reused for another requst
1586 * yet, in which case it still has &finished.
1587 *
1588 * 2. The slot may already be in-use to serve another request,
1589 * which can further be divided into two cases:
1590 *
1591 * (a) If call run_active_slot() hasn't been called for that
1592 * other request, slot->finished would have been cleared
1593 * by get_active_slot() and has NULL.
1594 *
1595 * (b) If the request did call run_active_slot(), then the
1596 * call would have updated slot->finished at the beginning
1597 * of this function, and with the clearing of the member
1598 * below, we would find that slot->finished is now NULL.
1599 *
1600 * In all cases, slot->finished has no useful information to
1601 * anybody at this point. Some compilers warn us for
1602 * attempting to smuggle a pointer that is about to become
1603 * invalid, i.e. &finished. We clear it here to assure them.
1604 */
1605 slot->finished = NULL;
1606 }
1607
1608 static void release_active_slot(struct active_request_slot *slot)
1609 {
1610 closedown_active_slot(slot);
1611 if (slot->curl) {
1612 xmulti_remove_handle(slot);
1613 if (curl_session_count > min_curl_sessions) {
1614 curl_easy_cleanup(slot->curl);
1615 slot->curl = NULL;
1616 curl_session_count--;
1617 }
1618 }
1619 fill_active_slots();
1620 }
1621
1622 void finish_all_active_slots(void)
1623 {
1624 struct active_request_slot *slot = active_queue_head;
1625
1626 while (slot != NULL)
1627 if (slot->in_use) {
1628 run_active_slot(slot);
1629 slot = active_queue_head;
1630 } else {
1631 slot = slot->next;
1632 }
1633 }
1634
1635 /* Helpers for modifying and creating URLs */
1636 static inline int needs_quote(int ch)
1637 {
1638 if (((ch >= 'A') && (ch <= 'Z'))
1639 || ((ch >= 'a') && (ch <= 'z'))
1640 || ((ch >= '0') && (ch <= '9'))
1641 || (ch == '/')
1642 || (ch == '-')
1643 || (ch == '.'))
1644 return 0;
1645 return 1;
1646 }
1647
1648 static char *quote_ref_url(const char *base, const char *ref)
1649 {
1650 struct strbuf buf = STRBUF_INIT;
1651 const char *cp;
1652 int ch;
1653
1654 end_url_with_slash(&buf, base);
1655
1656 for (cp = ref; (ch = *cp) != 0; cp++)
1657 if (needs_quote(ch))
1658 strbuf_addf(&buf, "%%%02x", ch);
1659 else
1660 strbuf_addch(&buf, *cp);
1661
1662 return strbuf_detach(&buf, NULL);
1663 }
1664
1665 void append_remote_object_url(struct strbuf *buf, const char *url,
1666 const char *hex,
1667 int only_two_digit_prefix)
1668 {
1669 end_url_with_slash(buf, url);
1670
1671 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1672 if (!only_two_digit_prefix)
1673 strbuf_addstr(buf, hex + 2);
1674 }
1675
1676 char *get_remote_object_url(const char *url, const char *hex,
1677 int only_two_digit_prefix)
1678 {
1679 struct strbuf buf = STRBUF_INIT;
1680 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1681 return strbuf_detach(&buf, NULL);
1682 }
1683
1684 void normalize_curl_result(CURLcode *result, long http_code,
1685 char *errorstr, size_t errorlen)
1686 {
1687 /*
1688 * If we see a failing http code with CURLE_OK, we have turned off
1689 * FAILONERROR (to keep the server's custom error response), and should
1690 * translate the code into failure here.
1691 *
1692 * Likewise, if we see a redirect (30x code), that means we turned off
1693 * redirect-following, and we should treat the result as an error.
1694 */
1695 if (*result == CURLE_OK && http_code >= 300) {
1696 *result = CURLE_HTTP_RETURNED_ERROR;
1697 /*
1698 * Normally curl will already have put the "reason phrase"
1699 * from the server into curl_errorstr; unfortunately without
1700 * FAILONERROR it is lost, so we can give only the numeric
1701 * status code.
1702 */
1703 xsnprintf(errorstr, errorlen,
1704 "The requested URL returned error: %ld",
1705 http_code);
1706 }
1707 }
1708
1709 static int handle_curl_result(struct slot_results *results)
1710 {
1711 normalize_curl_result(&results->curl_result, results->http_code,
1712 curl_errorstr, sizeof(curl_errorstr));
1713
1714 if (results->curl_result == CURLE_OK) {
1715 credential_approve(&http_auth);
1716 credential_approve(&proxy_auth);
1717 credential_approve(&cert_auth);
1718 return HTTP_OK;
1719 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1720 /*
1721 * We can't tell from here whether it's a bad path, bad
1722 * certificate, bad password, or something else wrong
1723 * with the certificate. So we reject the credential to
1724 * avoid caching or saving a bad password.
1725 */
1726 credential_reject(&cert_auth);
1727 return HTTP_NOAUTH;
1728 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1729 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1730 return HTTP_NOMATCHPUBLICKEY;
1731 #endif
1732 } else if (missing_target(results))
1733 return HTTP_MISSING_TARGET;
1734 else if (results->http_code == 401) {
1735 if (http_auth.username && http_auth.password) {
1736 credential_reject(&http_auth);
1737 return HTTP_NOAUTH;
1738 } else {
1739 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1740 if (results->auth_avail) {
1741 http_auth_methods &= results->auth_avail;
1742 http_auth_methods_restricted = 1;
1743 }
1744 return HTTP_REAUTH;
1745 }
1746 } else {
1747 if (results->http_connectcode == 407)
1748 credential_reject(&proxy_auth);
1749 if (!curl_errorstr[0])
1750 strlcpy(curl_errorstr,
1751 curl_easy_strerror(results->curl_result),
1752 sizeof(curl_errorstr));
1753 return HTTP_ERROR;
1754 }
1755 }
1756
1757 int run_one_slot(struct active_request_slot *slot,
1758 struct slot_results *results)
1759 {
1760 slot->results = results;
1761 if (!start_active_slot(slot)) {
1762 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1763 "failed to start HTTP request");
1764 return HTTP_START_FAILED;
1765 }
1766
1767 run_active_slot(slot);
1768 return handle_curl_result(results);
1769 }
1770
1771 struct curl_slist *http_copy_default_headers(void)
1772 {
1773 struct curl_slist *headers = NULL;
1774 const struct string_list_item *item;
1775
1776 for_each_string_list_item(item, &extra_http_headers)
1777 headers = curl_slist_append(headers, item->string);
1778
1779 return headers;
1780 }
1781
1782 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1783 {
1784 char *ptr;
1785 CURLcode ret;
1786
1787 strbuf_reset(buf);
1788 ret = curl_easy_getinfo(curl, info, &ptr);
1789 if (!ret && ptr)
1790 strbuf_addstr(buf, ptr);
1791 return ret;
1792 }
1793
1794 /*
1795 * Check for and extract a content-type parameter. "raw"
1796 * should be positioned at the start of the potential
1797 * parameter, with any whitespace already removed.
1798 *
1799 * "name" is the name of the parameter. The value is appended
1800 * to "out".
1801 */
1802 static int extract_param(const char *raw, const char *name,
1803 struct strbuf *out)
1804 {
1805 size_t len = strlen(name);
1806
1807 if (strncasecmp(raw, name, len))
1808 return -1;
1809 raw += len;
1810
1811 if (*raw != '=')
1812 return -1;
1813 raw++;
1814
1815 while (*raw && !isspace(*raw) && *raw != ';')
1816 strbuf_addch(out, *raw++);
1817 return 0;
1818 }
1819
1820 /*
1821 * Extract a normalized version of the content type, with any
1822 * spaces suppressed, all letters lowercased, and no trailing ";"
1823 * or parameters.
1824 *
1825 * Note that we will silently remove even invalid whitespace. For
1826 * example, "text / plain" is specifically forbidden by RFC 2616,
1827 * but "text/plain" is the only reasonable output, and this keeps
1828 * our code simple.
1829 *
1830 * If the "charset" argument is not NULL, store the value of any
1831 * charset parameter there.
1832 *
1833 * Example:
1834 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1835 * "text / plain" -> "text/plain"
1836 */
1837 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1838 struct strbuf *charset)
1839 {
1840 const char *p;
1841
1842 strbuf_reset(type);
1843 strbuf_grow(type, raw->len);
1844 for (p = raw->buf; *p; p++) {
1845 if (isspace(*p))
1846 continue;
1847 if (*p == ';') {
1848 p++;
1849 break;
1850 }
1851 strbuf_addch(type, tolower(*p));
1852 }
1853
1854 if (!charset)
1855 return;
1856
1857 strbuf_reset(charset);
1858 while (*p) {
1859 while (isspace(*p) || *p == ';')
1860 p++;
1861 if (!extract_param(p, "charset", charset))
1862 return;
1863 while (*p && !isspace(*p))
1864 p++;
1865 }
1866
1867 if (!charset->len && starts_with(type->buf, "text/"))
1868 strbuf_addstr(charset, "ISO-8859-1");
1869 }
1870
1871 static void write_accept_language(struct strbuf *buf)
1872 {
1873 /*
1874 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1875 * that, q-value will be smaller than 0.001, the minimum q-value the
1876 * HTTP specification allows. See
1877 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1878 */
1879 const int MAX_DECIMAL_PLACES = 3;
1880 const int MAX_LANGUAGE_TAGS = 1000;
1881 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1882 char **language_tags = NULL;
1883 int num_langs = 0;
1884 const char *s = get_preferred_languages();
1885 int i;
1886 struct strbuf tag = STRBUF_INIT;
1887
1888 /* Don't add Accept-Language header if no language is preferred. */
1889 if (!s)
1890 return;
1891
1892 /*
1893 * Split the colon-separated string of preferred languages into
1894 * language_tags array.
1895 */
1896 do {
1897 /* collect language tag */
1898 for (; *s && (isalnum(*s) || *s == '_'); s++)
1899 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1900
1901 /* skip .codeset, @modifier and any other unnecessary parts */
1902 while (*s && *s != ':')
1903 s++;
1904
1905 if (tag.len) {
1906 num_langs++;
1907 REALLOC_ARRAY(language_tags, num_langs);
1908 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1909 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1910 break;
1911 }
1912 } while (*s++);
1913
1914 /* write Accept-Language header into buf */
1915 if (num_langs) {
1916 int last_buf_len = 0;
1917 int max_q;
1918 int decimal_places;
1919 char q_format[32];
1920
1921 /* add '*' */
1922 REALLOC_ARRAY(language_tags, num_langs + 1);
1923 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1924
1925 /* compute decimal_places */
1926 for (max_q = 1, decimal_places = 0;
1927 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1928 decimal_places++, max_q *= 10)
1929 ;
1930
1931 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1932
1933 strbuf_addstr(buf, "Accept-Language: ");
1934
1935 for (i = 0; i < num_langs; i++) {
1936 if (i > 0)
1937 strbuf_addstr(buf, ", ");
1938
1939 strbuf_addstr(buf, language_tags[i]);
1940
1941 if (i > 0)
1942 strbuf_addf(buf, q_format, max_q - i);
1943
1944 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1945 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1946 break;
1947 }
1948
1949 last_buf_len = buf->len;
1950 }
1951 }
1952
1953 /* free language tags -- last one is a static '*' */
1954 for (i = 0; i < num_langs - 1; i++)
1955 free(language_tags[i]);
1956 free(language_tags);
1957 }
1958
1959 /*
1960 * Get an Accept-Language header which indicates user's preferred languages.
1961 *
1962 * Examples:
1963 * LANGUAGE= -> ""
1964 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1965 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1966 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1967 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1968 * LANGUAGE= LANG=C -> ""
1969 */
1970 const char *http_get_accept_language_header(void)
1971 {
1972 if (!cached_accept_language) {
1973 struct strbuf buf = STRBUF_INIT;
1974 write_accept_language(&buf);
1975 if (buf.len > 0)
1976 cached_accept_language = strbuf_detach(&buf, NULL);
1977 }
1978
1979 return cached_accept_language;
1980 }
1981
1982 static void http_opt_request_remainder(CURL *curl, off_t pos)
1983 {
1984 char buf[128];
1985 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1986 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1987 }
1988
1989 /* http_request() targets */
1990 #define HTTP_REQUEST_STRBUF 0
1991 #define HTTP_REQUEST_FILE 1
1992
1993 static int http_request(const char *url,
1994 void *result, int target,
1995 const struct http_get_options *options)
1996 {
1997 struct active_request_slot *slot;
1998 struct slot_results results;
1999 struct curl_slist *headers = http_copy_default_headers();
2000 struct strbuf buf = STRBUF_INIT;
2001 const char *accept_language;
2002 int ret;
2003
2004 slot = get_active_slot();
2005 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2006
2007 if (!result) {
2008 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2009 } else {
2010 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2011 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2012
2013 if (target == HTTP_REQUEST_FILE) {
2014 off_t posn = ftello(result);
2015 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2016 fwrite);
2017 if (posn > 0)
2018 http_opt_request_remainder(slot->curl, posn);
2019 } else
2020 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2021 fwrite_buffer);
2022 }
2023
2024 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2025
2026 accept_language = http_get_accept_language_header();
2027
2028 if (accept_language)
2029 headers = curl_slist_append(headers, accept_language);
2030
2031 strbuf_addstr(&buf, "Pragma:");
2032 if (options && options->no_cache)
2033 strbuf_addstr(&buf, " no-cache");
2034 if (options && options->initial_request &&
2035 http_follow_config == HTTP_FOLLOW_INITIAL)
2036 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2037
2038 headers = curl_slist_append(headers, buf.buf);
2039
2040 /* Add additional headers here */
2041 if (options && options->extra_headers) {
2042 const struct string_list_item *item;
2043 for_each_string_list_item(item, options->extra_headers) {
2044 headers = curl_slist_append(headers, item->string);
2045 }
2046 }
2047
2048 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2049 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2050 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2051 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2052
2053 ret = run_one_slot(slot, &results);
2054
2055 if (options && options->content_type) {
2056 struct strbuf raw = STRBUF_INIT;
2057 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2058 extract_content_type(&raw, options->content_type,
2059 options->charset);
2060 strbuf_release(&raw);
2061 }
2062
2063 if (options && options->effective_url)
2064 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2065 options->effective_url);
2066
2067 curl_slist_free_all(headers);
2068 strbuf_release(&buf);
2069
2070 return ret;
2071 }
2072
2073 /*
2074 * Update the "base" url to a more appropriate value, as deduced by
2075 * redirects seen when requesting a URL starting with "url".
2076 *
2077 * The "asked" parameter is a URL that we asked curl to access, and must begin
2078 * with "base".
2079 *
2080 * The "got" parameter is the URL that curl reported to us as where we ended
2081 * up.
2082 *
2083 * Returns 1 if we updated the base url, 0 otherwise.
2084 *
2085 * Our basic strategy is to compare "base" and "asked" to find the bits
2086 * specific to our request. We then strip those bits off of "got" to yield the
2087 * new base. So for example, if our base is "http://example.com/foo.git",
2088 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2089 * with "https://other.example.com/foo.git/info/refs". We would want the
2090 * new URL to become "https://other.example.com/foo.git".
2091 *
2092 * Note that this assumes a sane redirect scheme. It's entirely possible
2093 * in the example above to end up at a URL that does not even end in
2094 * "info/refs". In such a case we die. There's not much we can do, such a
2095 * scheme is unlikely to represent a real git repository, and failing to
2096 * rewrite the base opens options for malicious redirects to do funny things.
2097 */
2098 static int update_url_from_redirect(struct strbuf *base,
2099 const char *asked,
2100 const struct strbuf *got)
2101 {
2102 const char *tail;
2103 size_t new_len;
2104
2105 if (!strcmp(asked, got->buf))
2106 return 0;
2107
2108 if (!skip_prefix(asked, base->buf, &tail))
2109 BUG("update_url_from_redirect: %s is not a superset of %s",
2110 asked, base->buf);
2111
2112 new_len = got->len;
2113 if (!strip_suffix_mem(got->buf, &new_len, tail))
2114 die(_("unable to update url base from redirection:\n"
2115 " asked for: %s\n"
2116 " redirect: %s"),
2117 asked, got->buf);
2118
2119 strbuf_reset(base);
2120 strbuf_add(base, got->buf, new_len);
2121
2122 return 1;
2123 }
2124
2125 static int http_request_reauth(const char *url,
2126 void *result, int target,
2127 struct http_get_options *options)
2128 {
2129 int ret = http_request(url, result, target, options);
2130
2131 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2132 return ret;
2133
2134 if (options && options->effective_url && options->base_url) {
2135 if (update_url_from_redirect(options->base_url,
2136 url, options->effective_url)) {
2137 credential_from_url(&http_auth, options->base_url->buf);
2138 url = options->effective_url->buf;
2139 }
2140 }
2141
2142 if (ret != HTTP_REAUTH)
2143 return ret;
2144
2145 /*
2146 * The previous request may have put cruft into our output stream; we
2147 * should clear it out before making our next request.
2148 */
2149 switch (target) {
2150 case HTTP_REQUEST_STRBUF:
2151 strbuf_reset(result);
2152 break;
2153 case HTTP_REQUEST_FILE:
2154 if (fflush(result)) {
2155 error_errno("unable to flush a file");
2156 return HTTP_START_FAILED;
2157 }
2158 rewind(result);
2159 if (ftruncate(fileno(result), 0) < 0) {
2160 error_errno("unable to truncate a file");
2161 return HTTP_START_FAILED;
2162 }
2163 break;
2164 default:
2165 BUG("Unknown http_request target");
2166 }
2167
2168 credential_fill(&http_auth);
2169
2170 return http_request(url, result, target, options);
2171 }
2172
2173 int http_get_strbuf(const char *url,
2174 struct strbuf *result,
2175 struct http_get_options *options)
2176 {
2177 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2178 }
2179
2180 /*
2181 * Downloads a URL and stores the result in the given file.
2182 *
2183 * If a previous interrupted download is detected (i.e. a previous temporary
2184 * file is still around) the download is resumed.
2185 */
2186 int http_get_file(const char *url, const char *filename,
2187 struct http_get_options *options)
2188 {
2189 int ret;
2190 struct strbuf tmpfile = STRBUF_INIT;
2191 FILE *result;
2192
2193 strbuf_addf(&tmpfile, "%s.temp", filename);
2194 result = fopen(tmpfile.buf, "a");
2195 if (!result) {
2196 error("Unable to open local file %s", tmpfile.buf);
2197 ret = HTTP_ERROR;
2198 goto cleanup;
2199 }
2200
2201 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2202 fclose(result);
2203
2204 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2205 ret = HTTP_ERROR;
2206 cleanup:
2207 strbuf_release(&tmpfile);
2208 return ret;
2209 }
2210
2211 int http_fetch_ref(const char *base, struct ref *ref)
2212 {
2213 struct http_get_options options = {0};
2214 char *url;
2215 struct strbuf buffer = STRBUF_INIT;
2216 int ret = -1;
2217
2218 options.no_cache = 1;
2219
2220 url = quote_ref_url(base, ref->name);
2221 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2222 strbuf_rtrim(&buffer);
2223 if (buffer.len == the_hash_algo->hexsz)
2224 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2225 else if (starts_with(buffer.buf, "ref: ")) {
2226 ref->symref = xstrdup(buffer.buf + 5);
2227 ret = 0;
2228 }
2229 }
2230
2231 strbuf_release(&buffer);
2232 free(url);
2233 return ret;
2234 }
2235
2236 /* Helpers for fetching packs */
2237 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2238 {
2239 char *url, *tmp;
2240 struct strbuf buf = STRBUF_INIT;
2241
2242 if (http_is_verbose)
2243 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2244
2245 end_url_with_slash(&buf, base_url);
2246 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2247 url = strbuf_detach(&buf, NULL);
2248
2249 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2250 tmp = strbuf_detach(&buf, NULL);
2251
2252 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2253 error("Unable to get pack index %s", url);
2254 FREE_AND_NULL(tmp);
2255 }
2256
2257 free(url);
2258 return tmp;
2259 }
2260
2261 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2262 unsigned char *sha1, const char *base_url)
2263 {
2264 struct packed_git *new_pack;
2265 char *tmp_idx = NULL;
2266 int ret;
2267
2268 if (has_pack_index(sha1)) {
2269 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2270 if (!new_pack)
2271 return -1; /* parse_pack_index() already issued error message */
2272 goto add_pack;
2273 }
2274
2275 tmp_idx = fetch_pack_index(sha1, base_url);
2276 if (!tmp_idx)
2277 return -1;
2278
2279 new_pack = parse_pack_index(sha1, tmp_idx);
2280 if (!new_pack) {
2281 unlink(tmp_idx);
2282 free(tmp_idx);
2283
2284 return -1; /* parse_pack_index() already issued error message */
2285 }
2286
2287 ret = verify_pack_index(new_pack);
2288 if (!ret) {
2289 close_pack_index(new_pack);
2290 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2291 }
2292 free(tmp_idx);
2293 if (ret)
2294 return -1;
2295
2296 add_pack:
2297 new_pack->next = *packs_head;
2298 *packs_head = new_pack;
2299 return 0;
2300 }
2301
2302 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2303 {
2304 struct http_get_options options = {0};
2305 int ret = 0;
2306 char *url;
2307 const char *data;
2308 struct strbuf buf = STRBUF_INIT;
2309 struct object_id oid;
2310
2311 end_url_with_slash(&buf, base_url);
2312 strbuf_addstr(&buf, "objects/info/packs");
2313 url = strbuf_detach(&buf, NULL);
2314
2315 options.no_cache = 1;
2316 ret = http_get_strbuf(url, &buf, &options);
2317 if (ret != HTTP_OK)
2318 goto cleanup;
2319
2320 data = buf.buf;
2321 while (*data) {
2322 if (skip_prefix(data, "P pack-", &data) &&
2323 !parse_oid_hex(data, &oid, &data) &&
2324 skip_prefix(data, ".pack", &data) &&
2325 (*data == '\n' || *data == '\0')) {
2326 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2327 } else {
2328 data = strchrnul(data, '\n');
2329 }
2330 if (*data)
2331 data++; /* skip past newline */
2332 }
2333
2334 cleanup:
2335 free(url);
2336 return ret;
2337 }
2338
2339 void release_http_pack_request(struct http_pack_request *preq)
2340 {
2341 if (preq->packfile) {
2342 fclose(preq->packfile);
2343 preq->packfile = NULL;
2344 }
2345 preq->slot = NULL;
2346 strbuf_release(&preq->tmpfile);
2347 free(preq->url);
2348 free(preq);
2349 }
2350
2351 static const char *default_index_pack_args[] =
2352 {"index-pack", "--stdin", NULL};
2353
2354 int finish_http_pack_request(struct http_pack_request *preq)
2355 {
2356 struct child_process ip = CHILD_PROCESS_INIT;
2357 int tmpfile_fd;
2358 int ret = 0;
2359
2360 fclose(preq->packfile);
2361 preq->packfile = NULL;
2362
2363 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2364
2365 ip.git_cmd = 1;
2366 ip.in = tmpfile_fd;
2367 strvec_pushv(&ip.args, preq->index_pack_args ?
2368 preq->index_pack_args :
2369 default_index_pack_args);
2370
2371 if (preq->preserve_index_pack_stdout)
2372 ip.out = 0;
2373 else
2374 ip.no_stdout = 1;
2375
2376 if (run_command(&ip)) {
2377 ret = -1;
2378 goto cleanup;
2379 }
2380
2381 cleanup:
2382 close(tmpfile_fd);
2383 unlink(preq->tmpfile.buf);
2384 return ret;
2385 }
2386
2387 void http_install_packfile(struct packed_git *p,
2388 struct packed_git **list_to_remove_from)
2389 {
2390 struct packed_git **lst = list_to_remove_from;
2391
2392 while (*lst != p)
2393 lst = &((*lst)->next);
2394 *lst = (*lst)->next;
2395
2396 install_packed_git(the_repository, p);
2397 }
2398
2399 struct http_pack_request *new_http_pack_request(
2400 const unsigned char *packed_git_hash, const char *base_url) {
2401
2402 struct strbuf buf = STRBUF_INIT;
2403
2404 end_url_with_slash(&buf, base_url);
2405 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2406 hash_to_hex(packed_git_hash));
2407 return new_direct_http_pack_request(packed_git_hash,
2408 strbuf_detach(&buf, NULL));
2409 }
2410
2411 struct http_pack_request *new_direct_http_pack_request(
2412 const unsigned char *packed_git_hash, char *url)
2413 {
2414 off_t prev_posn = 0;
2415 struct http_pack_request *preq;
2416
2417 CALLOC_ARRAY(preq, 1);
2418 strbuf_init(&preq->tmpfile, 0);
2419
2420 preq->url = url;
2421
2422 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2423 preq->packfile = fopen(preq->tmpfile.buf, "a");
2424 if (!preq->packfile) {
2425 error("Unable to open local file %s for pack",
2426 preq->tmpfile.buf);
2427 goto abort;
2428 }
2429
2430 preq->slot = get_active_slot();
2431 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2432 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2433 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2434 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2435 no_pragma_header);
2436
2437 /*
2438 * If there is data present from a previous transfer attempt,
2439 * resume where it left off
2440 */
2441 prev_posn = ftello(preq->packfile);
2442 if (prev_posn>0) {
2443 if (http_is_verbose)
2444 fprintf(stderr,
2445 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2446 hash_to_hex(packed_git_hash),
2447 (uintmax_t)prev_posn);
2448 http_opt_request_remainder(preq->slot->curl, prev_posn);
2449 }
2450
2451 return preq;
2452
2453 abort:
2454 strbuf_release(&preq->tmpfile);
2455 free(preq->url);
2456 free(preq);
2457 return NULL;
2458 }
2459
2460 /* Helpers for fetching objects (loose) */
2461 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2462 void *data)
2463 {
2464 unsigned char expn[4096];
2465 size_t size = eltsize * nmemb;
2466 int posn = 0;
2467 struct http_object_request *freq = data;
2468 struct active_request_slot *slot = freq->slot;
2469
2470 if (slot) {
2471 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2472 &slot->http_code);
2473 if (c != CURLE_OK)
2474 BUG("curl_easy_getinfo for HTTP code failed: %s",
2475 curl_easy_strerror(c));
2476 if (slot->http_code >= 300)
2477 return nmemb;
2478 }
2479
2480 do {
2481 ssize_t retval = xwrite(freq->localfile,
2482 (char *) ptr + posn, size - posn);
2483 if (retval < 0)
2484 return posn / eltsize;
2485 posn += retval;
2486 } while (posn < size);
2487
2488 freq->stream.avail_in = size;
2489 freq->stream.next_in = (void *)ptr;
2490 do {
2491 freq->stream.next_out = expn;
2492 freq->stream.avail_out = sizeof(expn);
2493 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2494 the_hash_algo->update_fn(&freq->c, expn,
2495 sizeof(expn) - freq->stream.avail_out);
2496 } while (freq->stream.avail_in && freq->zret == Z_OK);
2497 return nmemb;
2498 }
2499
2500 struct http_object_request *new_http_object_request(const char *base_url,
2501 const struct object_id *oid)
2502 {
2503 char *hex = oid_to_hex(oid);
2504 struct strbuf filename = STRBUF_INIT;
2505 struct strbuf prevfile = STRBUF_INIT;
2506 int prevlocal;
2507 char prev_buf[PREV_BUF_SIZE];
2508 ssize_t prev_read = 0;
2509 off_t prev_posn = 0;
2510 struct http_object_request *freq;
2511
2512 CALLOC_ARRAY(freq, 1);
2513 strbuf_init(&freq->tmpfile, 0);
2514 oidcpy(&freq->oid, oid);
2515 freq->localfile = -1;
2516
2517 loose_object_path(the_repository, &filename, oid);
2518 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2519
2520 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2521 unlink_or_warn(prevfile.buf);
2522 rename(freq->tmpfile.buf, prevfile.buf);
2523 unlink_or_warn(freq->tmpfile.buf);
2524 strbuf_release(&filename);
2525
2526 if (freq->localfile != -1)
2527 error("fd leakage in start: %d", freq->localfile);
2528 freq->localfile = open(freq->tmpfile.buf,
2529 O_WRONLY | O_CREAT | O_EXCL, 0666);
2530 /*
2531 * This could have failed due to the "lazy directory creation";
2532 * try to mkdir the last path component.
2533 */
2534 if (freq->localfile < 0 && errno == ENOENT) {
2535 char *dir = strrchr(freq->tmpfile.buf, '/');
2536 if (dir) {
2537 *dir = 0;
2538 mkdir(freq->tmpfile.buf, 0777);
2539 *dir = '/';
2540 }
2541 freq->localfile = open(freq->tmpfile.buf,
2542 O_WRONLY | O_CREAT | O_EXCL, 0666);
2543 }
2544
2545 if (freq->localfile < 0) {
2546 error_errno("Couldn't create temporary file %s",
2547 freq->tmpfile.buf);
2548 goto abort;
2549 }
2550
2551 git_inflate_init(&freq->stream);
2552
2553 the_hash_algo->init_fn(&freq->c);
2554
2555 freq->url = get_remote_object_url(base_url, hex, 0);
2556
2557 /*
2558 * If a previous temp file is present, process what was already
2559 * fetched.
2560 */
2561 prevlocal = open(prevfile.buf, O_RDONLY);
2562 if (prevlocal != -1) {
2563 do {
2564 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2565 if (prev_read>0) {
2566 if (fwrite_sha1_file(prev_buf,
2567 1,
2568 prev_read,
2569 freq) == prev_read) {
2570 prev_posn += prev_read;
2571 } else {
2572 prev_read = -1;
2573 }
2574 }
2575 } while (prev_read > 0);
2576 close(prevlocal);
2577 }
2578 unlink_or_warn(prevfile.buf);
2579 strbuf_release(&prevfile);
2580
2581 /*
2582 * Reset inflate/SHA1 if there was an error reading the previous temp
2583 * file; also rewind to the beginning of the local file.
2584 */
2585 if (prev_read == -1) {
2586 memset(&freq->stream, 0, sizeof(freq->stream));
2587 git_inflate_init(&freq->stream);
2588 the_hash_algo->init_fn(&freq->c);
2589 if (prev_posn>0) {
2590 prev_posn = 0;
2591 lseek(freq->localfile, 0, SEEK_SET);
2592 if (ftruncate(freq->localfile, 0) < 0) {
2593 error_errno("Couldn't truncate temporary file %s",
2594 freq->tmpfile.buf);
2595 goto abort;
2596 }
2597 }
2598 }
2599
2600 freq->slot = get_active_slot();
2601
2602 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2603 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2604 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2605 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2606 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2607 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2608
2609 /*
2610 * If we have successfully processed data from a previous fetch
2611 * attempt, only fetch the data we don't already have.
2612 */
2613 if (prev_posn>0) {
2614 if (http_is_verbose)
2615 fprintf(stderr,
2616 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2617 hex, (uintmax_t)prev_posn);
2618 http_opt_request_remainder(freq->slot->curl, prev_posn);
2619 }
2620
2621 return freq;
2622
2623 abort:
2624 strbuf_release(&prevfile);
2625 free(freq->url);
2626 free(freq);
2627 return NULL;
2628 }
2629
2630 void process_http_object_request(struct http_object_request *freq)
2631 {
2632 if (!freq->slot)
2633 return;
2634 freq->curl_result = freq->slot->curl_result;
2635 freq->http_code = freq->slot->http_code;
2636 freq->slot = NULL;
2637 }
2638
2639 int finish_http_object_request(struct http_object_request *freq)
2640 {
2641 struct stat st;
2642 struct strbuf filename = STRBUF_INIT;
2643
2644 close(freq->localfile);
2645 freq->localfile = -1;
2646
2647 process_http_object_request(freq);
2648
2649 if (freq->http_code == 416) {
2650 warning("requested range invalid; we may already have all the data.");
2651 } else if (freq->curl_result != CURLE_OK) {
2652 if (stat(freq->tmpfile.buf, &st) == 0)
2653 if (st.st_size == 0)
2654 unlink_or_warn(freq->tmpfile.buf);
2655 return -1;
2656 }
2657
2658 git_inflate_end(&freq->stream);
2659 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2660 if (freq->zret != Z_STREAM_END) {
2661 unlink_or_warn(freq->tmpfile.buf);
2662 return -1;
2663 }
2664 if (!oideq(&freq->oid, &freq->real_oid)) {
2665 unlink_or_warn(freq->tmpfile.buf);
2666 return -1;
2667 }
2668 loose_object_path(the_repository, &filename, &freq->oid);
2669 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2670 strbuf_release(&filename);
2671
2672 return freq->rename;
2673 }
2674
2675 void abort_http_object_request(struct http_object_request *freq)
2676 {
2677 unlink_or_warn(freq->tmpfile.buf);
2678
2679 release_http_object_request(freq);
2680 }
2681
2682 void release_http_object_request(struct http_object_request *freq)
2683 {
2684 if (freq->localfile != -1) {
2685 close(freq->localfile);
2686 freq->localfile = -1;
2687 }
2688 FREE_AND_NULL(freq->url);
2689 if (freq->slot) {
2690 freq->slot->callback_func = NULL;
2691 freq->slot->callback_data = NULL;
2692 release_active_slot(freq->slot);
2693 freq->slot = NULL;
2694 }
2695 strbuf_release(&freq->tmpfile);
2696 }