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