Merge branch 'js/mingw-http-ssl'
[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.username = xstrdup("");
558                 cert_auth.path = xstrdup(ssl_cert);
559                 credential_fill(&cert_auth);
560         }
561         return 1;
562 }
563
564 #if LIBCURL_VERSION_NUM >= 0x071900
565 static void set_curl_keepalive(CURL *c)
566 {
567         curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
568 }
569
570 #elif LIBCURL_VERSION_NUM >= 0x071000
571 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
572 {
573         int ka = 1;
574         int rc;
575         socklen_t len = (socklen_t)sizeof(ka);
576
577         if (type != CURLSOCKTYPE_IPCXN)
578                 return 0;
579
580         rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
581         if (rc < 0)
582                 warning_errno("unable to set SO_KEEPALIVE on socket");
583
584         return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
585 }
586
587 static void set_curl_keepalive(CURL *c)
588 {
589         curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
590 }
591
592 #else
593 static void set_curl_keepalive(CURL *c)
594 {
595         /* not supported on older curl versions */
596 }
597 #endif
598
599 static void redact_sensitive_header(struct strbuf *header)
600 {
601         const char *sensitive_header;
602
603         if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
604             skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
605                 /* The first token is the type, which is OK to log */
606                 while (isspace(*sensitive_header))
607                         sensitive_header++;
608                 while (*sensitive_header && !isspace(*sensitive_header))
609                         sensitive_header++;
610                 /* Everything else is opaque and possibly sensitive */
611                 strbuf_setlen(header,  sensitive_header - header->buf);
612                 strbuf_addstr(header, " <redacted>");
613         } else if (cookies_to_redact.nr &&
614                    skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
615                 struct strbuf redacted_header = STRBUF_INIT;
616                 char *cookie;
617
618                 while (isspace(*sensitive_header))
619                         sensitive_header++;
620
621                 /*
622                  * The contents of header starting from sensitive_header will
623                  * subsequently be overridden, so it is fine to mutate this
624                  * string (hence the assignment to "char *").
625                  */
626                 cookie = (char *) sensitive_header;
627
628                 while (cookie) {
629                         char *equals;
630                         char *semicolon = strstr(cookie, "; ");
631                         if (semicolon)
632                                 *semicolon = 0;
633                         equals = strchrnul(cookie, '=');
634                         if (!equals) {
635                                 /* invalid cookie, just append and continue */
636                                 strbuf_addstr(&redacted_header, cookie);
637                                 continue;
638                         }
639                         *equals = 0; /* temporarily set to NUL for lookup */
640                         if (string_list_lookup(&cookies_to_redact, cookie)) {
641                                 strbuf_addstr(&redacted_header, cookie);
642                                 strbuf_addstr(&redacted_header, "=<redacted>");
643                         } else {
644                                 *equals = '=';
645                                 strbuf_addstr(&redacted_header, cookie);
646                         }
647                         if (semicolon) {
648                                 /*
649                                  * There are more cookies. (Or, for some
650                                  * reason, the input string ends in "; ".)
651                                  */
652                                 strbuf_addstr(&redacted_header, "; ");
653                                 cookie = semicolon + strlen("; ");
654                         } else {
655                                 cookie = NULL;
656                         }
657                 }
658
659                 strbuf_setlen(header, sensitive_header - header->buf);
660                 strbuf_addbuf(header, &redacted_header);
661         }
662 }
663
664 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
665 {
666         struct strbuf out = STRBUF_INIT;
667         struct strbuf **headers, **header;
668
669         strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
670                 text, (long)size, (long)size);
671         trace_strbuf(&trace_curl, &out);
672         strbuf_reset(&out);
673         strbuf_add(&out, ptr, size);
674         headers = strbuf_split_max(&out, '\n', 0);
675
676         for (header = headers; *header; header++) {
677                 if (hide_sensitive_header)
678                         redact_sensitive_header(*header);
679                 strbuf_insert((*header), 0, text, strlen(text));
680                 strbuf_insert((*header), strlen(text), ": ", 2);
681                 strbuf_rtrim((*header));
682                 strbuf_addch((*header), '\n');
683                 trace_strbuf(&trace_curl, (*header));
684         }
685         strbuf_list_free(headers);
686         strbuf_release(&out);
687 }
688
689 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
690 {
691         size_t i;
692         struct strbuf out = STRBUF_INIT;
693         unsigned int width = 60;
694
695         strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
696                 text, (long)size, (long)size);
697         trace_strbuf(&trace_curl, &out);
698
699         for (i = 0; i < size; i += width) {
700                 size_t w;
701
702                 strbuf_reset(&out);
703                 strbuf_addf(&out, "%s: ", text);
704                 for (w = 0; (w < width) && (i + w < size); w++) {
705                         unsigned char ch = ptr[i + w];
706
707                         strbuf_addch(&out,
708                                        (ch >= 0x20) && (ch < 0x80)
709                                        ? ch : '.');
710                 }
711                 strbuf_addch(&out, '\n');
712                 trace_strbuf(&trace_curl, &out);
713         }
714         strbuf_release(&out);
715 }
716
717 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
718 {
719         const char *text;
720         enum { NO_FILTER = 0, DO_FILTER = 1 };
721
722         switch (type) {
723         case CURLINFO_TEXT:
724                 trace_printf_key(&trace_curl, "== Info: %s", data);
725                 break;
726         case CURLINFO_HEADER_OUT:
727                 text = "=> Send header";
728                 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
729                 break;
730         case CURLINFO_DATA_OUT:
731                 if (trace_curl_data) {
732                         text = "=> Send data";
733                         curl_dump_data(text, (unsigned char *)data, size);
734                 }
735                 break;
736         case CURLINFO_SSL_DATA_OUT:
737                 if (trace_curl_data) {
738                         text = "=> Send SSL data";
739                         curl_dump_data(text, (unsigned char *)data, size);
740                 }
741                 break;
742         case CURLINFO_HEADER_IN:
743                 text = "<= Recv header";
744                 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
745                 break;
746         case CURLINFO_DATA_IN:
747                 if (trace_curl_data) {
748                         text = "<= Recv data";
749                         curl_dump_data(text, (unsigned char *)data, size);
750                 }
751                 break;
752         case CURLINFO_SSL_DATA_IN:
753                 if (trace_curl_data) {
754                         text = "<= Recv SSL data";
755                         curl_dump_data(text, (unsigned char *)data, size);
756                 }
757                 break;
758
759         default:                /* we ignore unknown types by default */
760                 return 0;
761         }
762         return 0;
763 }
764
765 void setup_curl_trace(CURL *handle)
766 {
767         if (!trace_want(&trace_curl))
768                 return;
769         curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
770         curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
771         curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
772 }
773
774 #ifdef CURLPROTO_HTTP
775 static long get_curl_allowed_protocols(int from_user)
776 {
777         long allowed_protocols = 0;
778
779         if (is_transport_allowed("http", from_user))
780                 allowed_protocols |= CURLPROTO_HTTP;
781         if (is_transport_allowed("https", from_user))
782                 allowed_protocols |= CURLPROTO_HTTPS;
783         if (is_transport_allowed("ftp", from_user))
784                 allowed_protocols |= CURLPROTO_FTP;
785         if (is_transport_allowed("ftps", from_user))
786                 allowed_protocols |= CURLPROTO_FTPS;
787
788         return allowed_protocols;
789 }
790 #endif
791
792 static CURL *get_curl_handle(void)
793 {
794         CURL *result = curl_easy_init();
795
796         if (!result)
797                 die("curl_easy_init failed");
798
799         if (!curl_ssl_verify) {
800                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
801                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
802         } else {
803                 /* Verify authenticity of the peer's certificate */
804                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
805                 /* The name in the cert must match whom we tried to connect */
806                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
807         }
808
809 #if LIBCURL_VERSION_NUM >= 0x070907
810         curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
811 #endif
812 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
813         curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
814 #endif
815
816 #ifdef CURLGSSAPI_DELEGATION_FLAG
817         if (curl_deleg) {
818                 int i;
819                 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
820                         if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
821                                 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
822                                                 curl_deleg_levels[i].curl_deleg_param);
823                                 break;
824                         }
825                 }
826                 if (i == ARRAY_SIZE(curl_deleg_levels))
827                         warning("Unknown delegation method '%s': using default",
828                                 curl_deleg);
829         }
830 #endif
831
832         if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
833             !http_schannel_check_revoke) {
834 #if LIBCURL_VERSION_NUM >= 0x072c00
835                 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
836 #else
837                 warning("CURLSSLOPT_NO_REVOKE not applied to curl SSL options because\n"
838                         "your curl version is too old (< 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 applied to curl redirects because\n"
912                 "your curl version is too old (>= 7.19.4)");
913 #endif
914         if (getenv("GIT_CURL_VERBOSE"))
915                 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
916         setup_curl_trace(result);
917         if (getenv("GIT_TRACE_CURL_NO_DATA"))
918                 trace_curl_data = 0;
919         if (getenv("GIT_REDACT_COOKIES")) {
920                 string_list_split(&cookies_to_redact,
921                                   getenv("GIT_REDACT_COOKIES"), ',', -1);
922                 string_list_sort(&cookies_to_redact);
923         }
924
925         curl_easy_setopt(result, CURLOPT_USERAGENT,
926                 user_agent ? user_agent : git_user_agent());
927
928         if (curl_ftp_no_epsv)
929                 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
930
931 #ifdef CURLOPT_USE_SSL
932         if (curl_ssl_try)
933                 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
934 #endif
935
936         /*
937          * CURL also examines these variables as a fallback; but we need to query
938          * them here in order to decide whether to prompt for missing password (cf.
939          * init_curl_proxy_auth()).
940          *
941          * Unlike many other common environment variables, these are historically
942          * lowercase only. It appears that CURL did not know this and implemented
943          * only uppercase variants, which was later corrected to take both - with
944          * the exception of http_proxy, which is lowercase only also in CURL. As
945          * the lowercase versions are the historical quasi-standard, they take
946          * precedence here, as in CURL.
947          */
948         if (!curl_http_proxy) {
949                 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
950                         var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
951                         var_override(&curl_http_proxy, getenv("https_proxy"));
952                 } else {
953                         var_override(&curl_http_proxy, getenv("http_proxy"));
954                 }
955                 if (!curl_http_proxy) {
956                         var_override(&curl_http_proxy, getenv("ALL_PROXY"));
957                         var_override(&curl_http_proxy, getenv("all_proxy"));
958                 }
959         }
960
961         if (curl_http_proxy && curl_http_proxy[0] == '\0') {
962                 /*
963                  * Handle case with the empty http.proxy value here to keep
964                  * common code clean.
965                  * NB: empty option disables proxying at all.
966                  */
967                 curl_easy_setopt(result, CURLOPT_PROXY, "");
968         } else if (curl_http_proxy) {
969 #if LIBCURL_VERSION_NUM >= 0x071800
970                 if (starts_with(curl_http_proxy, "socks5h"))
971                         curl_easy_setopt(result,
972                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
973                 else if (starts_with(curl_http_proxy, "socks5"))
974                         curl_easy_setopt(result,
975                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
976                 else if (starts_with(curl_http_proxy, "socks4a"))
977                         curl_easy_setopt(result,
978                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
979                 else if (starts_with(curl_http_proxy, "socks"))
980                         curl_easy_setopt(result,
981                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
982 #endif
983 #if LIBCURL_VERSION_NUM >= 0x073400
984                 else if (starts_with(curl_http_proxy, "https"))
985                         curl_easy_setopt(result,
986                                 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
987 #endif
988                 if (strstr(curl_http_proxy, "://"))
989                         credential_from_url(&proxy_auth, curl_http_proxy);
990                 else {
991                         struct strbuf url = STRBUF_INIT;
992                         strbuf_addf(&url, "http://%s", curl_http_proxy);
993                         credential_from_url(&proxy_auth, url.buf);
994                         strbuf_release(&url);
995                 }
996
997                 if (!proxy_auth.host)
998                         die("Invalid proxy URL '%s'", curl_http_proxy);
999
1000                 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1001 #if LIBCURL_VERSION_NUM >= 0x071304
1002                 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1003                 var_override(&curl_no_proxy, getenv("no_proxy"));
1004                 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1005 #endif
1006         }
1007         init_curl_proxy_auth(result);
1008
1009         set_curl_keepalive(result);
1010
1011         return result;
1012 }
1013
1014 static void set_from_env(const char **var, const char *envname)
1015 {
1016         const char *val = getenv(envname);
1017         if (val)
1018                 *var = val;
1019 }
1020
1021 void http_init(struct remote *remote, const char *url, int proactive_auth)
1022 {
1023         char *low_speed_limit;
1024         char *low_speed_time;
1025         char *normalized_url;
1026         struct urlmatch_config config = { STRING_LIST_INIT_DUP };
1027
1028         config.section = "http";
1029         config.key = NULL;
1030         config.collect_fn = http_options;
1031         config.cascade_fn = git_default_config;
1032         config.cb = NULL;
1033
1034         http_is_verbose = 0;
1035         normalized_url = url_normalize(url, &config.url);
1036
1037         git_config(urlmatch_config_entry, &config);
1038         free(normalized_url);
1039
1040 #if LIBCURL_VERSION_NUM >= 0x073800
1041         if (http_ssl_backend) {
1042                 const curl_ssl_backend **backends;
1043                 struct strbuf buf = STRBUF_INIT;
1044                 int i;
1045
1046                 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1047                 case CURLSSLSET_UNKNOWN_BACKEND:
1048                         strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1049                                             "Supported SSL backends:"),
1050                                             http_ssl_backend);
1051                         for (i = 0; backends[i]; i++)
1052                                 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1053                         die("%s", buf.buf);
1054                 case CURLSSLSET_NO_BACKENDS:
1055                         die(_("Could not set SSL backend to '%s': "
1056                               "cURL was built without SSL backends"),
1057                             http_ssl_backend);
1058                 case CURLSSLSET_TOO_LATE:
1059                         die(_("Could not set SSL backend to '%s': already set"),
1060                             http_ssl_backend);
1061                 case CURLSSLSET_OK:
1062                         break; /* Okay! */
1063                 }
1064         }
1065 #endif
1066
1067         if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1068                 die("curl_global_init failed");
1069
1070         http_proactive_auth = proactive_auth;
1071
1072         if (remote && remote->http_proxy)
1073                 curl_http_proxy = xstrdup(remote->http_proxy);
1074
1075         if (remote)
1076                 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1077
1078         pragma_header = curl_slist_append(http_copy_default_headers(),
1079                 "Pragma: no-cache");
1080         no_pragma_header = curl_slist_append(http_copy_default_headers(),
1081                 "Pragma:");
1082
1083 #ifdef USE_CURL_MULTI
1084         {
1085                 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1086                 if (http_max_requests != NULL)
1087                         max_requests = atoi(http_max_requests);
1088         }
1089
1090         curlm = curl_multi_init();
1091         if (!curlm)
1092                 die("curl_multi_init failed");
1093 #endif
1094
1095         if (getenv("GIT_SSL_NO_VERIFY"))
1096                 curl_ssl_verify = 0;
1097
1098         set_from_env(&ssl_cert, "GIT_SSL_CERT");
1099 #if LIBCURL_VERSION_NUM >= 0x070903
1100         set_from_env(&ssl_key, "GIT_SSL_KEY");
1101 #endif
1102 #if LIBCURL_VERSION_NUM >= 0x070908
1103         set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1104 #endif
1105         set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1106
1107         set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1108
1109         low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1110         if (low_speed_limit != NULL)
1111                 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1112         low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1113         if (low_speed_time != NULL)
1114                 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1115
1116         if (curl_ssl_verify == -1)
1117                 curl_ssl_verify = 1;
1118
1119         curl_session_count = 0;
1120 #ifdef USE_CURL_MULTI
1121         if (max_requests < 1)
1122                 max_requests = DEFAULT_MAX_REQUESTS;
1123 #endif
1124
1125         if (getenv("GIT_CURL_FTP_NO_EPSV"))
1126                 curl_ftp_no_epsv = 1;
1127
1128         if (url) {
1129                 credential_from_url(&http_auth, url);
1130                 if (!ssl_cert_password_required &&
1131                     getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1132                     starts_with(url, "https://"))
1133                         ssl_cert_password_required = 1;
1134         }
1135
1136 #ifndef NO_CURL_EASY_DUPHANDLE
1137         curl_default = get_curl_handle();
1138 #endif
1139 }
1140
1141 void http_cleanup(void)
1142 {
1143         struct active_request_slot *slot = active_queue_head;
1144
1145         while (slot != NULL) {
1146                 struct active_request_slot *next = slot->next;
1147                 if (slot->curl != NULL) {
1148                         xmulti_remove_handle(slot);
1149                         curl_easy_cleanup(slot->curl);
1150                 }
1151                 free(slot);
1152                 slot = next;
1153         }
1154         active_queue_head = NULL;
1155
1156 #ifndef NO_CURL_EASY_DUPHANDLE
1157         curl_easy_cleanup(curl_default);
1158 #endif
1159
1160 #ifdef USE_CURL_MULTI
1161         curl_multi_cleanup(curlm);
1162 #endif
1163         curl_global_cleanup();
1164
1165         curl_slist_free_all(extra_http_headers);
1166         extra_http_headers = NULL;
1167
1168         curl_slist_free_all(pragma_header);
1169         pragma_header = NULL;
1170
1171         curl_slist_free_all(no_pragma_header);
1172         no_pragma_header = NULL;
1173
1174         if (curl_http_proxy) {
1175                 free((void *)curl_http_proxy);
1176                 curl_http_proxy = NULL;
1177         }
1178
1179         if (proxy_auth.password) {
1180                 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1181                 FREE_AND_NULL(proxy_auth.password);
1182         }
1183
1184         free((void *)curl_proxyuserpwd);
1185         curl_proxyuserpwd = NULL;
1186
1187         free((void *)http_proxy_authmethod);
1188         http_proxy_authmethod = NULL;
1189
1190         if (cert_auth.password != NULL) {
1191                 memset(cert_auth.password, 0, strlen(cert_auth.password));
1192                 FREE_AND_NULL(cert_auth.password);
1193         }
1194         ssl_cert_password_required = 0;
1195
1196         FREE_AND_NULL(cached_accept_language);
1197 }
1198
1199 struct active_request_slot *get_active_slot(void)
1200 {
1201         struct active_request_slot *slot = active_queue_head;
1202         struct active_request_slot *newslot;
1203
1204 #ifdef USE_CURL_MULTI
1205         int num_transfers;
1206
1207         /* Wait for a slot to open up if the queue is full */
1208         while (active_requests >= max_requests) {
1209                 curl_multi_perform(curlm, &num_transfers);
1210                 if (num_transfers < active_requests)
1211                         process_curl_messages();
1212         }
1213 #endif
1214
1215         while (slot != NULL && slot->in_use)
1216                 slot = slot->next;
1217
1218         if (slot == NULL) {
1219                 newslot = xmalloc(sizeof(*newslot));
1220                 newslot->curl = NULL;
1221                 newslot->in_use = 0;
1222                 newslot->next = NULL;
1223
1224                 slot = active_queue_head;
1225                 if (slot == NULL) {
1226                         active_queue_head = newslot;
1227                 } else {
1228                         while (slot->next != NULL)
1229                                 slot = slot->next;
1230                         slot->next = newslot;
1231                 }
1232                 slot = newslot;
1233         }
1234
1235         if (slot->curl == NULL) {
1236 #ifdef NO_CURL_EASY_DUPHANDLE
1237                 slot->curl = get_curl_handle();
1238 #else
1239                 slot->curl = curl_easy_duphandle(curl_default);
1240 #endif
1241                 curl_session_count++;
1242         }
1243
1244         active_requests++;
1245         slot->in_use = 1;
1246         slot->results = NULL;
1247         slot->finished = NULL;
1248         slot->callback_data = NULL;
1249         slot->callback_func = NULL;
1250         curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1251         if (curl_save_cookies)
1252                 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1253         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1254         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1255         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1256         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1257         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1258         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1259         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1260         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1261         curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1262         curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1263
1264         /*
1265          * Default following to off unless "ALWAYS" is configured; this gives
1266          * callers a sane starting point, and they can tweak for individual
1267          * HTTP_FOLLOW_* cases themselves.
1268          */
1269         if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1270                 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1271         else
1272                 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1273
1274 #if LIBCURL_VERSION_NUM >= 0x070a08
1275         curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1276 #endif
1277 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1278         curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1279 #endif
1280         if (http_auth.password || curl_empty_auth_enabled())
1281                 init_curl_http_auth(slot->curl);
1282
1283         return slot;
1284 }
1285
1286 int start_active_slot(struct active_request_slot *slot)
1287 {
1288 #ifdef USE_CURL_MULTI
1289         CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1290         int num_transfers;
1291
1292         if (curlm_result != CURLM_OK &&
1293             curlm_result != CURLM_CALL_MULTI_PERFORM) {
1294                 warning("curl_multi_add_handle failed: %s",
1295                         curl_multi_strerror(curlm_result));
1296                 active_requests--;
1297                 slot->in_use = 0;
1298                 return 0;
1299         }
1300
1301         /*
1302          * We know there must be something to do, since we just added
1303          * something.
1304          */
1305         curl_multi_perform(curlm, &num_transfers);
1306 #endif
1307         return 1;
1308 }
1309
1310 #ifdef USE_CURL_MULTI
1311 struct fill_chain {
1312         void *data;
1313         int (*fill)(void *);
1314         struct fill_chain *next;
1315 };
1316
1317 static struct fill_chain *fill_cfg;
1318
1319 void add_fill_function(void *data, int (*fill)(void *))
1320 {
1321         struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1322         struct fill_chain **linkp = &fill_cfg;
1323         new_fill->data = data;
1324         new_fill->fill = fill;
1325         new_fill->next = NULL;
1326         while (*linkp)
1327                 linkp = &(*linkp)->next;
1328         *linkp = new_fill;
1329 }
1330
1331 void fill_active_slots(void)
1332 {
1333         struct active_request_slot *slot = active_queue_head;
1334
1335         while (active_requests < max_requests) {
1336                 struct fill_chain *fill;
1337                 for (fill = fill_cfg; fill; fill = fill->next)
1338                         if (fill->fill(fill->data))
1339                                 break;
1340
1341                 if (!fill)
1342                         break;
1343         }
1344
1345         while (slot != NULL) {
1346                 if (!slot->in_use && slot->curl != NULL
1347                         && curl_session_count > min_curl_sessions) {
1348                         curl_easy_cleanup(slot->curl);
1349                         slot->curl = NULL;
1350                         curl_session_count--;
1351                 }
1352                 slot = slot->next;
1353         }
1354 }
1355
1356 void step_active_slots(void)
1357 {
1358         int num_transfers;
1359         CURLMcode curlm_result;
1360
1361         do {
1362                 curlm_result = curl_multi_perform(curlm, &num_transfers);
1363         } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1364         if (num_transfers < active_requests) {
1365                 process_curl_messages();
1366                 fill_active_slots();
1367         }
1368 }
1369 #endif
1370
1371 void run_active_slot(struct active_request_slot *slot)
1372 {
1373 #ifdef USE_CURL_MULTI
1374         fd_set readfds;
1375         fd_set writefds;
1376         fd_set excfds;
1377         int max_fd;
1378         struct timeval select_timeout;
1379         int finished = 0;
1380
1381         slot->finished = &finished;
1382         while (!finished) {
1383                 step_active_slots();
1384
1385                 if (slot->in_use) {
1386 #if LIBCURL_VERSION_NUM >= 0x070f04
1387                         long curl_timeout;
1388                         curl_multi_timeout(curlm, &curl_timeout);
1389                         if (curl_timeout == 0) {
1390                                 continue;
1391                         } else if (curl_timeout == -1) {
1392                                 select_timeout.tv_sec  = 0;
1393                                 select_timeout.tv_usec = 50000;
1394                         } else {
1395                                 select_timeout.tv_sec  =  curl_timeout / 1000;
1396                                 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1397                         }
1398 #else
1399                         select_timeout.tv_sec  = 0;
1400                         select_timeout.tv_usec = 50000;
1401 #endif
1402
1403                         max_fd = -1;
1404                         FD_ZERO(&readfds);
1405                         FD_ZERO(&writefds);
1406                         FD_ZERO(&excfds);
1407                         curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1408
1409                         /*
1410                          * It can happen that curl_multi_timeout returns a pathologically
1411                          * long timeout when curl_multi_fdset returns no file descriptors
1412                          * to read.  See commit message for more details.
1413                          */
1414                         if (max_fd < 0 &&
1415                             (select_timeout.tv_sec > 0 ||
1416                              select_timeout.tv_usec > 50000)) {
1417                                 select_timeout.tv_sec  = 0;
1418                                 select_timeout.tv_usec = 50000;
1419                         }
1420
1421                         select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1422                 }
1423         }
1424 #else
1425         while (slot->in_use) {
1426                 slot->curl_result = curl_easy_perform(slot->curl);
1427                 finish_active_slot(slot);
1428         }
1429 #endif
1430 }
1431
1432 static void release_active_slot(struct active_request_slot *slot)
1433 {
1434         closedown_active_slot(slot);
1435         if (slot->curl) {
1436                 xmulti_remove_handle(slot);
1437                 if (curl_session_count > min_curl_sessions) {
1438                         curl_easy_cleanup(slot->curl);
1439                         slot->curl = NULL;
1440                         curl_session_count--;
1441                 }
1442         }
1443 #ifdef USE_CURL_MULTI
1444         fill_active_slots();
1445 #endif
1446 }
1447
1448 void finish_all_active_slots(void)
1449 {
1450         struct active_request_slot *slot = active_queue_head;
1451
1452         while (slot != NULL)
1453                 if (slot->in_use) {
1454                         run_active_slot(slot);
1455                         slot = active_queue_head;
1456                 } else {
1457                         slot = slot->next;
1458                 }
1459 }
1460
1461 /* Helpers for modifying and creating URLs */
1462 static inline int needs_quote(int ch)
1463 {
1464         if (((ch >= 'A') && (ch <= 'Z'))
1465                         || ((ch >= 'a') && (ch <= 'z'))
1466                         || ((ch >= '0') && (ch <= '9'))
1467                         || (ch == '/')
1468                         || (ch == '-')
1469                         || (ch == '.'))
1470                 return 0;
1471         return 1;
1472 }
1473
1474 static char *quote_ref_url(const char *base, const char *ref)
1475 {
1476         struct strbuf buf = STRBUF_INIT;
1477         const char *cp;
1478         int ch;
1479
1480         end_url_with_slash(&buf, base);
1481
1482         for (cp = ref; (ch = *cp) != 0; cp++)
1483                 if (needs_quote(ch))
1484                         strbuf_addf(&buf, "%%%02x", ch);
1485                 else
1486                         strbuf_addch(&buf, *cp);
1487
1488         return strbuf_detach(&buf, NULL);
1489 }
1490
1491 void append_remote_object_url(struct strbuf *buf, const char *url,
1492                               const char *hex,
1493                               int only_two_digit_prefix)
1494 {
1495         end_url_with_slash(buf, url);
1496
1497         strbuf_addf(buf, "objects/%.*s/", 2, hex);
1498         if (!only_two_digit_prefix)
1499                 strbuf_addstr(buf, hex + 2);
1500 }
1501
1502 char *get_remote_object_url(const char *url, const char *hex,
1503                             int only_two_digit_prefix)
1504 {
1505         struct strbuf buf = STRBUF_INIT;
1506         append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1507         return strbuf_detach(&buf, NULL);
1508 }
1509
1510 static int handle_curl_result(struct slot_results *results)
1511 {
1512         /*
1513          * If we see a failing http code with CURLE_OK, we have turned off
1514          * FAILONERROR (to keep the server's custom error response), and should
1515          * translate the code into failure here.
1516          *
1517          * Likewise, if we see a redirect (30x code), that means we turned off
1518          * redirect-following, and we should treat the result as an error.
1519          */
1520         if (results->curl_result == CURLE_OK &&
1521             results->http_code >= 300) {
1522                 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1523                 /*
1524                  * Normally curl will already have put the "reason phrase"
1525                  * from the server into curl_errorstr; unfortunately without
1526                  * FAILONERROR it is lost, so we can give only the numeric
1527                  * status code.
1528                  */
1529                 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1530                           "The requested URL returned error: %ld",
1531                           results->http_code);
1532         }
1533
1534         if (results->curl_result == CURLE_OK) {
1535                 credential_approve(&http_auth);
1536                 if (proxy_auth.password)
1537                         credential_approve(&proxy_auth);
1538                 return HTTP_OK;
1539         } else if (missing_target(results))
1540                 return HTTP_MISSING_TARGET;
1541         else if (results->http_code == 401) {
1542                 if (http_auth.username && http_auth.password) {
1543                         credential_reject(&http_auth);
1544                         return HTTP_NOAUTH;
1545                 } else {
1546 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1547                         http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1548                         if (results->auth_avail) {
1549                                 http_auth_methods &= results->auth_avail;
1550                                 http_auth_methods_restricted = 1;
1551                         }
1552 #endif
1553                         return HTTP_REAUTH;
1554                 }
1555         } else {
1556                 if (results->http_connectcode == 407)
1557                         credential_reject(&proxy_auth);
1558 #if LIBCURL_VERSION_NUM >= 0x070c00
1559                 if (!curl_errorstr[0])
1560                         strlcpy(curl_errorstr,
1561                                 curl_easy_strerror(results->curl_result),
1562                                 sizeof(curl_errorstr));
1563 #endif
1564                 return HTTP_ERROR;
1565         }
1566 }
1567
1568 int run_one_slot(struct active_request_slot *slot,
1569                  struct slot_results *results)
1570 {
1571         slot->results = results;
1572         if (!start_active_slot(slot)) {
1573                 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1574                           "failed to start HTTP request");
1575                 return HTTP_START_FAILED;
1576         }
1577
1578         run_active_slot(slot);
1579         return handle_curl_result(results);
1580 }
1581
1582 struct curl_slist *http_copy_default_headers(void)
1583 {
1584         struct curl_slist *headers = NULL, *h;
1585
1586         for (h = extra_http_headers; h; h = h->next)
1587                 headers = curl_slist_append(headers, h->data);
1588
1589         return headers;
1590 }
1591
1592 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1593 {
1594         char *ptr;
1595         CURLcode ret;
1596
1597         strbuf_reset(buf);
1598         ret = curl_easy_getinfo(curl, info, &ptr);
1599         if (!ret && ptr)
1600                 strbuf_addstr(buf, ptr);
1601         return ret;
1602 }
1603
1604 /*
1605  * Check for and extract a content-type parameter. "raw"
1606  * should be positioned at the start of the potential
1607  * parameter, with any whitespace already removed.
1608  *
1609  * "name" is the name of the parameter. The value is appended
1610  * to "out".
1611  */
1612 static int extract_param(const char *raw, const char *name,
1613                          struct strbuf *out)
1614 {
1615         size_t len = strlen(name);
1616
1617         if (strncasecmp(raw, name, len))
1618                 return -1;
1619         raw += len;
1620
1621         if (*raw != '=')
1622                 return -1;
1623         raw++;
1624
1625         while (*raw && !isspace(*raw) && *raw != ';')
1626                 strbuf_addch(out, *raw++);
1627         return 0;
1628 }
1629
1630 /*
1631  * Extract a normalized version of the content type, with any
1632  * spaces suppressed, all letters lowercased, and no trailing ";"
1633  * or parameters.
1634  *
1635  * Note that we will silently remove even invalid whitespace. For
1636  * example, "text / plain" is specifically forbidden by RFC 2616,
1637  * but "text/plain" is the only reasonable output, and this keeps
1638  * our code simple.
1639  *
1640  * If the "charset" argument is not NULL, store the value of any
1641  * charset parameter there.
1642  *
1643  * Example:
1644  *   "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1645  *   "text / plain" -> "text/plain"
1646  */
1647 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1648                                  struct strbuf *charset)
1649 {
1650         const char *p;
1651
1652         strbuf_reset(type);
1653         strbuf_grow(type, raw->len);
1654         for (p = raw->buf; *p; p++) {
1655                 if (isspace(*p))
1656                         continue;
1657                 if (*p == ';') {
1658                         p++;
1659                         break;
1660                 }
1661                 strbuf_addch(type, tolower(*p));
1662         }
1663
1664         if (!charset)
1665                 return;
1666
1667         strbuf_reset(charset);
1668         while (*p) {
1669                 while (isspace(*p) || *p == ';')
1670                         p++;
1671                 if (!extract_param(p, "charset", charset))
1672                         return;
1673                 while (*p && !isspace(*p))
1674                         p++;
1675         }
1676
1677         if (!charset->len && starts_with(type->buf, "text/"))
1678                 strbuf_addstr(charset, "ISO-8859-1");
1679 }
1680
1681 static void write_accept_language(struct strbuf *buf)
1682 {
1683         /*
1684          * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1685          * that, q-value will be smaller than 0.001, the minimum q-value the
1686          * HTTP specification allows. See
1687          * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1688          */
1689         const int MAX_DECIMAL_PLACES = 3;
1690         const int MAX_LANGUAGE_TAGS = 1000;
1691         const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1692         char **language_tags = NULL;
1693         int num_langs = 0;
1694         const char *s = get_preferred_languages();
1695         int i;
1696         struct strbuf tag = STRBUF_INIT;
1697
1698         /* Don't add Accept-Language header if no language is preferred. */
1699         if (!s)
1700                 return;
1701
1702         /*
1703          * Split the colon-separated string of preferred languages into
1704          * language_tags array.
1705          */
1706         do {
1707                 /* collect language tag */
1708                 for (; *s && (isalnum(*s) || *s == '_'); s++)
1709                         strbuf_addch(&tag, *s == '_' ? '-' : *s);
1710
1711                 /* skip .codeset, @modifier and any other unnecessary parts */
1712                 while (*s && *s != ':')
1713                         s++;
1714
1715                 if (tag.len) {
1716                         num_langs++;
1717                         REALLOC_ARRAY(language_tags, num_langs);
1718                         language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1719                         if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1720                                 break;
1721                 }
1722         } while (*s++);
1723
1724         /* write Accept-Language header into buf */
1725         if (num_langs) {
1726                 int last_buf_len = 0;
1727                 int max_q;
1728                 int decimal_places;
1729                 char q_format[32];
1730
1731                 /* add '*' */
1732                 REALLOC_ARRAY(language_tags, num_langs + 1);
1733                 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1734
1735                 /* compute decimal_places */
1736                 for (max_q = 1, decimal_places = 0;
1737                      max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1738                      decimal_places++, max_q *= 10)
1739                         ;
1740
1741                 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1742
1743                 strbuf_addstr(buf, "Accept-Language: ");
1744
1745                 for (i = 0; i < num_langs; i++) {
1746                         if (i > 0)
1747                                 strbuf_addstr(buf, ", ");
1748
1749                         strbuf_addstr(buf, language_tags[i]);
1750
1751                         if (i > 0)
1752                                 strbuf_addf(buf, q_format, max_q - i);
1753
1754                         if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1755                                 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1756                                 break;
1757                         }
1758
1759                         last_buf_len = buf->len;
1760                 }
1761         }
1762
1763         /* free language tags -- last one is a static '*' */
1764         for (i = 0; i < num_langs - 1; i++)
1765                 free(language_tags[i]);
1766         free(language_tags);
1767 }
1768
1769 /*
1770  * Get an Accept-Language header which indicates user's preferred languages.
1771  *
1772  * Examples:
1773  *   LANGUAGE= -> ""
1774  *   LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1775  *   LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1776  *   LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1777  *   LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1778  *   LANGUAGE= LANG=C -> ""
1779  */
1780 static const char *get_accept_language(void)
1781 {
1782         if (!cached_accept_language) {
1783                 struct strbuf buf = STRBUF_INIT;
1784                 write_accept_language(&buf);
1785                 if (buf.len > 0)
1786                         cached_accept_language = strbuf_detach(&buf, NULL);
1787         }
1788
1789         return cached_accept_language;
1790 }
1791
1792 static void http_opt_request_remainder(CURL *curl, off_t pos)
1793 {
1794         char buf[128];
1795         xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1796         curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1797 }
1798
1799 /* http_request() targets */
1800 #define HTTP_REQUEST_STRBUF     0
1801 #define HTTP_REQUEST_FILE       1
1802
1803 static int http_request(const char *url,
1804                         void *result, int target,
1805                         const struct http_get_options *options)
1806 {
1807         struct active_request_slot *slot;
1808         struct slot_results results;
1809         struct curl_slist *headers = http_copy_default_headers();
1810         struct strbuf buf = STRBUF_INIT;
1811         const char *accept_language;
1812         int ret;
1813
1814         slot = get_active_slot();
1815         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1816
1817         if (result == NULL) {
1818                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1819         } else {
1820                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1821                 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1822
1823                 if (target == HTTP_REQUEST_FILE) {
1824                         off_t posn = ftello(result);
1825                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1826                                          fwrite);
1827                         if (posn > 0)
1828                                 http_opt_request_remainder(slot->curl, posn);
1829                 } else
1830                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1831                                          fwrite_buffer);
1832         }
1833
1834         accept_language = get_accept_language();
1835
1836         if (accept_language)
1837                 headers = curl_slist_append(headers, accept_language);
1838
1839         strbuf_addstr(&buf, "Pragma:");
1840         if (options && options->no_cache)
1841                 strbuf_addstr(&buf, " no-cache");
1842         if (options && options->keep_error)
1843                 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1844         if (options && options->initial_request &&
1845             http_follow_config == HTTP_FOLLOW_INITIAL)
1846                 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1847
1848         headers = curl_slist_append(headers, buf.buf);
1849
1850         /* Add additional headers here */
1851         if (options && options->extra_headers) {
1852                 const struct string_list_item *item;
1853                 for_each_string_list_item(item, options->extra_headers) {
1854                         headers = curl_slist_append(headers, item->string);
1855                 }
1856         }
1857
1858         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1859         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1860         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1861
1862         ret = run_one_slot(slot, &results);
1863
1864         if (options && options->content_type) {
1865                 struct strbuf raw = STRBUF_INIT;
1866                 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1867                 extract_content_type(&raw, options->content_type,
1868                                      options->charset);
1869                 strbuf_release(&raw);
1870         }
1871
1872         if (options && options->effective_url)
1873                 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1874                                 options->effective_url);
1875
1876         curl_slist_free_all(headers);
1877         strbuf_release(&buf);
1878
1879         return ret;
1880 }
1881
1882 /*
1883  * Update the "base" url to a more appropriate value, as deduced by
1884  * redirects seen when requesting a URL starting with "url".
1885  *
1886  * The "asked" parameter is a URL that we asked curl to access, and must begin
1887  * with "base".
1888  *
1889  * The "got" parameter is the URL that curl reported to us as where we ended
1890  * up.
1891  *
1892  * Returns 1 if we updated the base url, 0 otherwise.
1893  *
1894  * Our basic strategy is to compare "base" and "asked" to find the bits
1895  * specific to our request. We then strip those bits off of "got" to yield the
1896  * new base. So for example, if our base is "http://example.com/foo.git",
1897  * and we ask for "http://example.com/foo.git/info/refs", we might end up
1898  * with "https://other.example.com/foo.git/info/refs". We would want the
1899  * new URL to become "https://other.example.com/foo.git".
1900  *
1901  * Note that this assumes a sane redirect scheme. It's entirely possible
1902  * in the example above to end up at a URL that does not even end in
1903  * "info/refs".  In such a case we die. There's not much we can do, such a
1904  * scheme is unlikely to represent a real git repository, and failing to
1905  * rewrite the base opens options for malicious redirects to do funny things.
1906  */
1907 static int update_url_from_redirect(struct strbuf *base,
1908                                     const char *asked,
1909                                     const struct strbuf *got)
1910 {
1911         const char *tail;
1912         size_t new_len;
1913
1914         if (!strcmp(asked, got->buf))
1915                 return 0;
1916
1917         if (!skip_prefix(asked, base->buf, &tail))
1918                 BUG("update_url_from_redirect: %s is not a superset of %s",
1919                     asked, base->buf);
1920
1921         new_len = got->len;
1922         if (!strip_suffix_mem(got->buf, &new_len, tail))
1923                 die(_("unable to update url base from redirection:\n"
1924                       "  asked for: %s\n"
1925                       "   redirect: %s"),
1926                     asked, got->buf);
1927
1928         strbuf_reset(base);
1929         strbuf_add(base, got->buf, new_len);
1930
1931         return 1;
1932 }
1933
1934 static int http_request_reauth(const char *url,
1935                                void *result, int target,
1936                                struct http_get_options *options)
1937 {
1938         int ret = http_request(url, result, target, options);
1939
1940         if (ret != HTTP_OK && ret != HTTP_REAUTH)
1941                 return ret;
1942
1943         if (options && options->effective_url && options->base_url) {
1944                 if (update_url_from_redirect(options->base_url,
1945                                              url, options->effective_url)) {
1946                         credential_from_url(&http_auth, options->base_url->buf);
1947                         url = options->effective_url->buf;
1948                 }
1949         }
1950
1951         if (ret != HTTP_REAUTH)
1952                 return ret;
1953
1954         /*
1955          * If we are using KEEP_ERROR, the previous request may have
1956          * put cruft into our output stream; we should clear it out before
1957          * making our next request. We only know how to do this for
1958          * the strbuf case, but that is enough to satisfy current callers.
1959          */
1960         if (options && options->keep_error) {
1961                 switch (target) {
1962                 case HTTP_REQUEST_STRBUF:
1963                         strbuf_reset(result);
1964                         break;
1965                 default:
1966                         BUG("HTTP_KEEP_ERROR is only supported with strbufs");
1967                 }
1968         }
1969
1970         credential_fill(&http_auth);
1971
1972         return http_request(url, result, target, options);
1973 }
1974
1975 int http_get_strbuf(const char *url,
1976                     struct strbuf *result,
1977                     struct http_get_options *options)
1978 {
1979         return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1980 }
1981
1982 /*
1983  * Downloads a URL and stores the result in the given file.
1984  *
1985  * If a previous interrupted download is detected (i.e. a previous temporary
1986  * file is still around) the download is resumed.
1987  */
1988 static int http_get_file(const char *url, const char *filename,
1989                          struct http_get_options *options)
1990 {
1991         int ret;
1992         struct strbuf tmpfile = STRBUF_INIT;
1993         FILE *result;
1994
1995         strbuf_addf(&tmpfile, "%s.temp", filename);
1996         result = fopen(tmpfile.buf, "a");
1997         if (!result) {
1998                 error("Unable to open local file %s", tmpfile.buf);
1999                 ret = HTTP_ERROR;
2000                 goto cleanup;
2001         }
2002
2003         ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2004         fclose(result);
2005
2006         if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2007                 ret = HTTP_ERROR;
2008 cleanup:
2009         strbuf_release(&tmpfile);
2010         return ret;
2011 }
2012
2013 int http_fetch_ref(const char *base, struct ref *ref)
2014 {
2015         struct http_get_options options = {0};
2016         char *url;
2017         struct strbuf buffer = STRBUF_INIT;
2018         int ret = -1;
2019
2020         options.no_cache = 1;
2021
2022         url = quote_ref_url(base, ref->name);
2023         if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2024                 strbuf_rtrim(&buffer);
2025                 if (buffer.len == 40)
2026                         ret = get_oid_hex(buffer.buf, &ref->old_oid);
2027                 else if (starts_with(buffer.buf, "ref: ")) {
2028                         ref->symref = xstrdup(buffer.buf + 5);
2029                         ret = 0;
2030                 }
2031         }
2032
2033         strbuf_release(&buffer);
2034         free(url);
2035         return ret;
2036 }
2037
2038 /* Helpers for fetching packs */
2039 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
2040 {
2041         char *url, *tmp;
2042         struct strbuf buf = STRBUF_INIT;
2043
2044         if (http_is_verbose)
2045                 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
2046
2047         end_url_with_slash(&buf, base_url);
2048         strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
2049         url = strbuf_detach(&buf, NULL);
2050
2051         strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
2052         tmp = strbuf_detach(&buf, NULL);
2053
2054         if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2055                 error("Unable to get pack index %s", url);
2056                 FREE_AND_NULL(tmp);
2057         }
2058
2059         free(url);
2060         return tmp;
2061 }
2062
2063 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2064         unsigned char *sha1, const char *base_url)
2065 {
2066         struct packed_git *new_pack;
2067         char *tmp_idx = NULL;
2068         int ret;
2069
2070         if (has_pack_index(sha1)) {
2071                 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2072                 if (!new_pack)
2073                         return -1; /* parse_pack_index() already issued error message */
2074                 goto add_pack;
2075         }
2076
2077         tmp_idx = fetch_pack_index(sha1, base_url);
2078         if (!tmp_idx)
2079                 return -1;
2080
2081         new_pack = parse_pack_index(sha1, tmp_idx);
2082         if (!new_pack) {
2083                 unlink(tmp_idx);
2084                 free(tmp_idx);
2085
2086                 return -1; /* parse_pack_index() already issued error message */
2087         }
2088
2089         ret = verify_pack_index(new_pack);
2090         if (!ret) {
2091                 close_pack_index(new_pack);
2092                 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2093         }
2094         free(tmp_idx);
2095         if (ret)
2096                 return -1;
2097
2098 add_pack:
2099         new_pack->next = *packs_head;
2100         *packs_head = new_pack;
2101         return 0;
2102 }
2103
2104 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2105 {
2106         struct http_get_options options = {0};
2107         int ret = 0, i = 0;
2108         char *url, *data;
2109         struct strbuf buf = STRBUF_INIT;
2110         unsigned char hash[GIT_MAX_RAWSZ];
2111         const unsigned hexsz = the_hash_algo->hexsz;
2112
2113         end_url_with_slash(&buf, base_url);
2114         strbuf_addstr(&buf, "objects/info/packs");
2115         url = strbuf_detach(&buf, NULL);
2116
2117         options.no_cache = 1;
2118         ret = http_get_strbuf(url, &buf, &options);
2119         if (ret != HTTP_OK)
2120                 goto cleanup;
2121
2122         data = buf.buf;
2123         while (i < buf.len) {
2124                 switch (data[i]) {
2125                 case 'P':
2126                         i++;
2127                         if (i + hexsz + 12 <= buf.len &&
2128                             starts_with(data + i, " pack-") &&
2129                             starts_with(data + i + hexsz + 6, ".pack\n")) {
2130                                 get_sha1_hex(data + i + 6, hash);
2131                                 fetch_and_setup_pack_index(packs_head, hash,
2132                                                       base_url);
2133                                 i += hexsz + 11;
2134                                 break;
2135                         }
2136                 default:
2137                         while (i < buf.len && data[i] != '\n')
2138                                 i++;
2139                 }
2140                 i++;
2141         }
2142
2143 cleanup:
2144         free(url);
2145         return ret;
2146 }
2147
2148 void release_http_pack_request(struct http_pack_request *preq)
2149 {
2150         if (preq->packfile != NULL) {
2151                 fclose(preq->packfile);
2152                 preq->packfile = NULL;
2153         }
2154         preq->slot = NULL;
2155         strbuf_release(&preq->tmpfile);
2156         free(preq->url);
2157         free(preq);
2158 }
2159
2160 int finish_http_pack_request(struct http_pack_request *preq)
2161 {
2162         struct packed_git **lst;
2163         struct packed_git *p = preq->target;
2164         char *tmp_idx;
2165         size_t len;
2166         struct child_process ip = CHILD_PROCESS_INIT;
2167
2168         close_pack_index(p);
2169
2170         fclose(preq->packfile);
2171         preq->packfile = NULL;
2172
2173         lst = preq->lst;
2174         while (*lst != p)
2175                 lst = &((*lst)->next);
2176         *lst = (*lst)->next;
2177
2178         if (!strip_suffix(preq->tmpfile.buf, ".pack.temp", &len))
2179                 BUG("pack tmpfile does not end in .pack.temp?");
2180         tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile.buf);
2181
2182         argv_array_push(&ip.args, "index-pack");
2183         argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2184         argv_array_push(&ip.args, preq->tmpfile.buf);
2185         ip.git_cmd = 1;
2186         ip.no_stdin = 1;
2187         ip.no_stdout = 1;
2188
2189         if (run_command(&ip)) {
2190                 unlink(preq->tmpfile.buf);
2191                 unlink(tmp_idx);
2192                 free(tmp_idx);
2193                 return -1;
2194         }
2195
2196         unlink(sha1_pack_index_name(p->sha1));
2197
2198         if (finalize_object_file(preq->tmpfile.buf, sha1_pack_name(p->sha1))
2199          || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2200                 free(tmp_idx);
2201                 return -1;
2202         }
2203
2204         install_packed_git(the_repository, p);
2205         free(tmp_idx);
2206         return 0;
2207 }
2208
2209 struct http_pack_request *new_http_pack_request(
2210         struct packed_git *target, const char *base_url)
2211 {
2212         off_t prev_posn = 0;
2213         struct strbuf buf = STRBUF_INIT;
2214         struct http_pack_request *preq;
2215
2216         preq = xcalloc(1, sizeof(*preq));
2217         strbuf_init(&preq->tmpfile, 0);
2218         preq->target = target;
2219
2220         end_url_with_slash(&buf, base_url);
2221         strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2222                 sha1_to_hex(target->sha1));
2223         preq->url = strbuf_detach(&buf, NULL);
2224
2225         strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(target->sha1));
2226         preq->packfile = fopen(preq->tmpfile.buf, "a");
2227         if (!preq->packfile) {
2228                 error("Unable to open local file %s for pack",
2229                       preq->tmpfile.buf);
2230                 goto abort;
2231         }
2232
2233         preq->slot = get_active_slot();
2234         curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2235         curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2236         curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2237         curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2238                 no_pragma_header);
2239
2240         /*
2241          * If there is data present from a previous transfer attempt,
2242          * resume where it left off
2243          */
2244         prev_posn = ftello(preq->packfile);
2245         if (prev_posn>0) {
2246                 if (http_is_verbose)
2247                         fprintf(stderr,
2248                                 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2249                                 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2250                 http_opt_request_remainder(preq->slot->curl, prev_posn);
2251         }
2252
2253         return preq;
2254
2255 abort:
2256         strbuf_release(&preq->tmpfile);
2257         free(preq->url);
2258         free(preq);
2259         return NULL;
2260 }
2261
2262 /* Helpers for fetching objects (loose) */
2263 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2264                                void *data)
2265 {
2266         unsigned char expn[4096];
2267         size_t size = eltsize * nmemb;
2268         int posn = 0;
2269         struct http_object_request *freq = data;
2270         struct active_request_slot *slot = freq->slot;
2271
2272         if (slot) {
2273                 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2274                                                 &slot->http_code);
2275                 if (c != CURLE_OK)
2276                         BUG("curl_easy_getinfo for HTTP code failed: %s",
2277                                 curl_easy_strerror(c));
2278                 if (slot->http_code >= 300)
2279                         return size;
2280         }
2281
2282         do {
2283                 ssize_t retval = xwrite(freq->localfile,
2284                                         (char *) ptr + posn, size - posn);
2285                 if (retval < 0)
2286                         return posn;
2287                 posn += retval;
2288         } while (posn < size);
2289
2290         freq->stream.avail_in = size;
2291         freq->stream.next_in = (void *)ptr;
2292         do {
2293                 freq->stream.next_out = expn;
2294                 freq->stream.avail_out = sizeof(expn);
2295                 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2296                 git_SHA1_Update(&freq->c, expn,
2297                                 sizeof(expn) - freq->stream.avail_out);
2298         } while (freq->stream.avail_in && freq->zret == Z_OK);
2299         return size;
2300 }
2301
2302 struct http_object_request *new_http_object_request(const char *base_url,
2303         unsigned char *sha1)
2304 {
2305         char *hex = sha1_to_hex(sha1);
2306         struct strbuf filename = STRBUF_INIT;
2307         struct strbuf prevfile = STRBUF_INIT;
2308         int prevlocal;
2309         char prev_buf[PREV_BUF_SIZE];
2310         ssize_t prev_read = 0;
2311         off_t prev_posn = 0;
2312         struct http_object_request *freq;
2313
2314         freq = xcalloc(1, sizeof(*freq));
2315         strbuf_init(&freq->tmpfile, 0);
2316         hashcpy(freq->sha1, sha1);
2317         freq->localfile = -1;
2318
2319         sha1_file_name(the_repository, &filename, sha1);
2320         strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2321
2322         strbuf_addf(&prevfile, "%s.prev", filename.buf);
2323         unlink_or_warn(prevfile.buf);
2324         rename(freq->tmpfile.buf, prevfile.buf);
2325         unlink_or_warn(freq->tmpfile.buf);
2326         strbuf_release(&filename);
2327
2328         if (freq->localfile != -1)
2329                 error("fd leakage in start: %d", freq->localfile);
2330         freq->localfile = open(freq->tmpfile.buf,
2331                                O_WRONLY | O_CREAT | O_EXCL, 0666);
2332         /*
2333          * This could have failed due to the "lazy directory creation";
2334          * try to mkdir the last path component.
2335          */
2336         if (freq->localfile < 0 && errno == ENOENT) {
2337                 char *dir = strrchr(freq->tmpfile.buf, '/');
2338                 if (dir) {
2339                         *dir = 0;
2340                         mkdir(freq->tmpfile.buf, 0777);
2341                         *dir = '/';
2342                 }
2343                 freq->localfile = open(freq->tmpfile.buf,
2344                                        O_WRONLY | O_CREAT | O_EXCL, 0666);
2345         }
2346
2347         if (freq->localfile < 0) {
2348                 error_errno("Couldn't create temporary file %s",
2349                             freq->tmpfile.buf);
2350                 goto abort;
2351         }
2352
2353         git_inflate_init(&freq->stream);
2354
2355         git_SHA1_Init(&freq->c);
2356
2357         freq->url = get_remote_object_url(base_url, hex, 0);
2358
2359         /*
2360          * If a previous temp file is present, process what was already
2361          * fetched.
2362          */
2363         prevlocal = open(prevfile.buf, O_RDONLY);
2364         if (prevlocal != -1) {
2365                 do {
2366                         prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2367                         if (prev_read>0) {
2368                                 if (fwrite_sha1_file(prev_buf,
2369                                                      1,
2370                                                      prev_read,
2371                                                      freq) == prev_read) {
2372                                         prev_posn += prev_read;
2373                                 } else {
2374                                         prev_read = -1;
2375                                 }
2376                         }
2377                 } while (prev_read > 0);
2378                 close(prevlocal);
2379         }
2380         unlink_or_warn(prevfile.buf);
2381         strbuf_release(&prevfile);
2382
2383         /*
2384          * Reset inflate/SHA1 if there was an error reading the previous temp
2385          * file; also rewind to the beginning of the local file.
2386          */
2387         if (prev_read == -1) {
2388                 memset(&freq->stream, 0, sizeof(freq->stream));
2389                 git_inflate_init(&freq->stream);
2390                 git_SHA1_Init(&freq->c);
2391                 if (prev_posn>0) {
2392                         prev_posn = 0;
2393                         lseek(freq->localfile, 0, SEEK_SET);
2394                         if (ftruncate(freq->localfile, 0) < 0) {
2395                                 error_errno("Couldn't truncate temporary file %s",
2396                                             freq->tmpfile.buf);
2397                                 goto abort;
2398                         }
2399                 }
2400         }
2401
2402         freq->slot = get_active_slot();
2403
2404         curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2405         curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2406         curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2407         curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2408         curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2409         curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2410
2411         /*
2412          * If we have successfully processed data from a previous fetch
2413          * attempt, only fetch the data we don't already have.
2414          */
2415         if (prev_posn>0) {
2416                 if (http_is_verbose)
2417                         fprintf(stderr,
2418                                 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2419                                 hex, (uintmax_t)prev_posn);
2420                 http_opt_request_remainder(freq->slot->curl, prev_posn);
2421         }
2422
2423         return freq;
2424
2425 abort:
2426         strbuf_release(&prevfile);
2427         free(freq->url);
2428         free(freq);
2429         return NULL;
2430 }
2431
2432 void process_http_object_request(struct http_object_request *freq)
2433 {
2434         if (freq->slot == NULL)
2435                 return;
2436         freq->curl_result = freq->slot->curl_result;
2437         freq->http_code = freq->slot->http_code;
2438         freq->slot = NULL;
2439 }
2440
2441 int finish_http_object_request(struct http_object_request *freq)
2442 {
2443         struct stat st;
2444         struct strbuf filename = STRBUF_INIT;
2445
2446         close(freq->localfile);
2447         freq->localfile = -1;
2448
2449         process_http_object_request(freq);
2450
2451         if (freq->http_code == 416) {
2452                 warning("requested range invalid; we may already have all the data.");
2453         } else if (freq->curl_result != CURLE_OK) {
2454                 if (stat(freq->tmpfile.buf, &st) == 0)
2455                         if (st.st_size == 0)
2456                                 unlink_or_warn(freq->tmpfile.buf);
2457                 return -1;
2458         }
2459
2460         git_inflate_end(&freq->stream);
2461         git_SHA1_Final(freq->real_sha1, &freq->c);
2462         if (freq->zret != Z_STREAM_END) {
2463                 unlink_or_warn(freq->tmpfile.buf);
2464                 return -1;
2465         }
2466         if (!hasheq(freq->sha1, freq->real_sha1)) {
2467                 unlink_or_warn(freq->tmpfile.buf);
2468                 return -1;
2469         }
2470         sha1_file_name(the_repository, &filename, freq->sha1);
2471         freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2472         strbuf_release(&filename);
2473
2474         return freq->rename;
2475 }
2476
2477 void abort_http_object_request(struct http_object_request *freq)
2478 {
2479         unlink_or_warn(freq->tmpfile.buf);
2480
2481         release_http_object_request(freq);
2482 }
2483
2484 void release_http_object_request(struct http_object_request *freq)
2485 {
2486         if (freq->localfile != -1) {
2487                 close(freq->localfile);
2488                 freq->localfile = -1;
2489         }
2490         FREE_AND_NULL(freq->url);
2491         if (freq->slot != NULL) {
2492                 freq->slot->callback_func = NULL;
2493                 freq->slot->callback_data = NULL;
2494                 release_active_slot(freq->slot);
2495                 freq->slot = NULL;
2496         }
2497         strbuf_release(&freq->tmpfile);
2498 }