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