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