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