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