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