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