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