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