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