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