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