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