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