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