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