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