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