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