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