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