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