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