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