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