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