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