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