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