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