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