Imported Upstream version 2.17.1
[platform/upstream/git.git] / http.c
diff --git a/http.c b/http.c
index 1044f9b..a5bd5d6 100644 (file)
--- a/http.c
+++ b/http.c
@@ -1,5 +1,6 @@
 #include "git-compat-util.h"
 #include "http.h"
+#include "config.h"
 #include "pack.h"
 #include "sideband.h"
 #include "run-command.h"
 #include "pkt-line.h"
 #include "gettext.h"
 #include "transport.h"
+#include "packfile.h"
+#include "protocol.h"
+#include "string-list.h"
 
+static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
+static int trace_curl_data = 1;
+static struct string_list cookies_to_redact = STRING_LIST_INIT_DUP;
 #if LIBCURL_VERSION_NUM >= 0x070a08
 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
 #else
@@ -18,7 +25,7 @@ long int git_curl_ipresolve;
 #endif
 int active_requests;
 int http_is_verbose;
-size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
+ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
 
 #if LIBCURL_VERSION_NUM >= 0x070a06
 #define LIBCURL_CAN_HANDLE_AUTH_ANY
@@ -62,6 +69,9 @@ static const char *ssl_key;
 #if LIBCURL_VERSION_NUM >= 0x070908
 static const char *ssl_capath;
 #endif
+#if LIBCURL_VERSION_NUM >= 0x071304
+static const char *curl_no_proxy;
+#endif
 #if LIBCURL_VERSION_NUM >= 0x072c00
 static const char *ssl_pinnedkey;
 #endif
@@ -70,7 +80,6 @@ static long curl_low_speed_limit = -1;
 static long curl_low_speed_time = -1;
 static int curl_ftp_no_epsv;
 static const char *curl_http_proxy;
-static const char *curl_no_proxy;
 static const char *http_proxy_authmethod;
 static struct {
        const char *name;
@@ -89,6 +98,18 @@ static struct {
         * here, too
         */
 };
+#ifdef CURLGSSAPI_DELEGATION_FLAG
+static const char *curl_deleg;
+static struct {
+       const char *name;
+       long curl_deleg_param;
+} curl_deleg_levels[] = {
+       { "none", CURLGSSAPI_DELEGATION_NONE },
+       { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
+       { "always", CURLGSSAPI_DELEGATION_FLAG },
+};
+#endif
+
 static struct credential proxy_auth = CREDENTIAL_INIT;
 static const char *curl_proxyuserpwd;
 static const char *curl_cookie_file;
@@ -96,7 +117,9 @@ static int curl_save_cookies;
 struct credential http_auth = CREDENTIAL_INIT;
 static int http_proactive_auth;
 static const char *user_agent;
-static int curl_empty_auth;
+static int curl_empty_auth = -1;
+
+enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
 
 #if LIBCURL_VERSION_NUM >= 0x071700
 /* Use CURLOPT_KEYPASSWD as is */
@@ -110,10 +133,19 @@ static struct credential cert_auth = CREDENTIAL_INIT;
 static int ssl_cert_password_required;
 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
 static unsigned long http_auth_methods = CURLAUTH_ANY;
+static int http_auth_methods_restricted;
+/* Modes for which empty_auth cannot actually help us. */
+static unsigned long empty_auth_useless =
+       CURLAUTH_BASIC
+#ifdef CURLAUTH_DIGEST_IE
+       | CURLAUTH_DIGEST_IE
+#endif
+       | CURLAUTH_DIGEST;
 #endif
 
 static struct curl_slist *pragma_header;
 static struct curl_slist *no_pragma_header;
+static struct curl_slist *extra_http_headers;
 
 static struct active_request_slot *active_queue_head;
 
@@ -199,6 +231,13 @@ static void finish_active_slot(struct active_request_slot *slot)
                slot->callback_func(slot->callback_data);
 }
 
+static void xmulti_remove_handle(struct active_request_slot *slot)
+{
+#ifdef USE_CURL_MULTI
+       curl_multi_remove_handle(curlm, slot->curl);
+#endif
+}
+
 #ifdef USE_CURL_MULTI
 static void process_curl_messages(void)
 {
@@ -214,7 +253,7 @@ static void process_curl_messages(void)
                               slot->curl != curl_message->easy_handle)
                                slot = slot->next;
                        if (slot != NULL) {
-                               curl_multi_remove_handle(curlm, slot->curl);
+                               xmulti_remove_handle(slot);
                                slot->curl_result = curl_result;
                                finish_active_slot(slot);
                        } else {
@@ -240,10 +279,10 @@ static int http_options(const char *var, const char *value, void *cb)
        if (!strcmp("http.sslversion", var))
                return git_config_string(&ssl_version, var, value);
        if (!strcmp("http.sslcert", var))
-               return git_config_string(&ssl_cert, var, value);
+               return git_config_pathname(&ssl_cert, var, value);
 #if LIBCURL_VERSION_NUM >= 0x070903
        if (!strcmp("http.sslkey", var))
-               return git_config_string(&ssl_key, var, value);
+               return git_config_pathname(&ssl_key, var, value);
 #endif
 #if LIBCURL_VERSION_NUM >= 0x070908
        if (!strcmp("http.sslcapath", var))
@@ -300,7 +339,9 @@ static int http_options(const char *var, const char *value, void *cb)
        }
 
        if (!strcmp("http.postbuffer", var)) {
-               http_post_buffer = git_config_int(var, value);
+               http_post_buffer = git_config_ssize_t(var, value);
+               if (http_post_buffer < 0)
+                       warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
                if (http_post_buffer < LARGE_PACKET_MAX)
                        http_post_buffer = LARGE_PACKET_MAX;
                return 0;
@@ -310,10 +351,22 @@ static int http_options(const char *var, const char *value, void *cb)
                return git_config_string(&user_agent, var, value);
 
        if (!strcmp("http.emptyauth", var)) {
-               curl_empty_auth = git_config_bool(var, value);
+               if (value && !strcmp("auto", value))
+                       curl_empty_auth = -1;
+               else
+                       curl_empty_auth = git_config_bool(var, value);
                return 0;
        }
 
+       if (!strcmp("http.delegation", var)) {
+#ifdef CURLGSSAPI_DELEGATION_FLAG
+               return git_config_string(&curl_deleg, var, value);
+#else
+               warning(_("Delegation control is not supported with cURL < 7.22.0"));
+               return 0;
+#endif
+       }
+
        if (!strcmp("http.pinnedpubkey", var)) {
 #if LIBCURL_VERSION_NUM >= 0x072c00
                return git_config_pathname(&ssl_pinnedkey, var, value);
@@ -323,14 +376,64 @@ static int http_options(const char *var, const char *value, void *cb)
 #endif
        }
 
+       if (!strcmp("http.extraheader", var)) {
+               if (!value) {
+                       return config_error_nonbool(var);
+               } else if (!*value) {
+                       curl_slist_free_all(extra_http_headers);
+                       extra_http_headers = NULL;
+               } else {
+                       extra_http_headers =
+                               curl_slist_append(extra_http_headers, value);
+               }
+               return 0;
+       }
+
+       if (!strcmp("http.followredirects", var)) {
+               if (value && !strcmp(value, "initial"))
+                       http_follow_config = HTTP_FOLLOW_INITIAL;
+               else if (git_config_bool(var, value))
+                       http_follow_config = HTTP_FOLLOW_ALWAYS;
+               else
+                       http_follow_config = HTTP_FOLLOW_NONE;
+               return 0;
+       }
+
        /* Fall back on the default ones */
        return git_default_config(var, value, cb);
 }
 
+static int curl_empty_auth_enabled(void)
+{
+       if (curl_empty_auth >= 0)
+               return curl_empty_auth;
+
+#ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
+       /*
+        * Our libcurl is too old to do AUTH_ANY in the first place;
+        * just default to turning the feature off.
+        */
+#else
+       /*
+        * In the automatic case, kick in the empty-auth
+        * hack as long as we would potentially try some
+        * method more exotic than "Basic" or "Digest".
+        *
+        * But only do this when this is our second or
+        * subsequent request, as by then we know what
+        * methods are available.
+        */
+       if (http_auth_methods_restricted &&
+           (http_auth_methods & ~empty_auth_useless))
+               return 1;
+#endif
+       return 0;
+}
+
 static void init_curl_http_auth(CURL *result)
 {
-       if (!http_auth.username) {
-               if (curl_empty_auth)
+       if (!http_auth.username || !*http_auth.username) {
+               if (curl_empty_auth_enabled())
                        curl_easy_setopt(result, CURLOPT_USERPWD, ":");
                return;
        }
@@ -446,8 +549,7 @@ static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
 
        rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
        if (rc < 0)
-               warning("unable to set SO_KEEPALIVE on socket %s",
-                       strerror(errno));
+               warning_errno("unable to set SO_KEEPALIVE on socket");
 
        return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
 }
@@ -464,10 +566,202 @@ static void set_curl_keepalive(CURL *c)
 }
 #endif
 
+static void redact_sensitive_header(struct strbuf *header)
+{
+       const char *sensitive_header;
+
+       if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
+           skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
+               /* The first token is the type, which is OK to log */
+               while (isspace(*sensitive_header))
+                       sensitive_header++;
+               while (*sensitive_header && !isspace(*sensitive_header))
+                       sensitive_header++;
+               /* Everything else is opaque and possibly sensitive */
+               strbuf_setlen(header,  sensitive_header - header->buf);
+               strbuf_addstr(header, " <redacted>");
+       } else if (cookies_to_redact.nr &&
+                  skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
+               struct strbuf redacted_header = STRBUF_INIT;
+               char *cookie;
+
+               while (isspace(*sensitive_header))
+                       sensitive_header++;
+
+               /*
+                * The contents of header starting from sensitive_header will
+                * subsequently be overridden, so it is fine to mutate this
+                * string (hence the assignment to "char *").
+                */
+               cookie = (char *) sensitive_header;
+
+               while (cookie) {
+                       char *equals;
+                       char *semicolon = strstr(cookie, "; ");
+                       if (semicolon)
+                               *semicolon = 0;
+                       equals = strchrnul(cookie, '=');
+                       if (!equals) {
+                               /* invalid cookie, just append and continue */
+                               strbuf_addstr(&redacted_header, cookie);
+                               continue;
+                       }
+                       *equals = 0; /* temporarily set to NUL for lookup */
+                       if (string_list_lookup(&cookies_to_redact, cookie)) {
+                               strbuf_addstr(&redacted_header, cookie);
+                               strbuf_addstr(&redacted_header, "=<redacted>");
+                       } else {
+                               *equals = '=';
+                               strbuf_addstr(&redacted_header, cookie);
+                       }
+                       if (semicolon) {
+                               /*
+                                * There are more cookies. (Or, for some
+                                * reason, the input string ends in "; ".)
+                                */
+                               strbuf_addstr(&redacted_header, "; ");
+                               cookie = semicolon + strlen("; ");
+                       } else {
+                               cookie = NULL;
+                       }
+               }
+
+               strbuf_setlen(header, sensitive_header - header->buf);
+               strbuf_addbuf(header, &redacted_header);
+       }
+}
+
+static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
+{
+       struct strbuf out = STRBUF_INIT;
+       struct strbuf **headers, **header;
+
+       strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
+               text, (long)size, (long)size);
+       trace_strbuf(&trace_curl, &out);
+       strbuf_reset(&out);
+       strbuf_add(&out, ptr, size);
+       headers = strbuf_split_max(&out, '\n', 0);
+
+       for (header = headers; *header; header++) {
+               if (hide_sensitive_header)
+                       redact_sensitive_header(*header);
+               strbuf_insert((*header), 0, text, strlen(text));
+               strbuf_insert((*header), strlen(text), ": ", 2);
+               strbuf_rtrim((*header));
+               strbuf_addch((*header), '\n');
+               trace_strbuf(&trace_curl, (*header));
+       }
+       strbuf_list_free(headers);
+       strbuf_release(&out);
+}
+
+static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
+{
+       size_t i;
+       struct strbuf out = STRBUF_INIT;
+       unsigned int width = 60;
+
+       strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
+               text, (long)size, (long)size);
+       trace_strbuf(&trace_curl, &out);
+
+       for (i = 0; i < size; i += width) {
+               size_t w;
+
+               strbuf_reset(&out);
+               strbuf_addf(&out, "%s: ", text);
+               for (w = 0; (w < width) && (i + w < size); w++) {
+                       unsigned char ch = ptr[i + w];
+
+                       strbuf_addch(&out,
+                                      (ch >= 0x20) && (ch < 0x80)
+                                      ? ch : '.');
+               }
+               strbuf_addch(&out, '\n');
+               trace_strbuf(&trace_curl, &out);
+       }
+       strbuf_release(&out);
+}
+
+static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
+{
+       const char *text;
+       enum { NO_FILTER = 0, DO_FILTER = 1 };
+
+       switch (type) {
+       case CURLINFO_TEXT:
+               trace_printf_key(&trace_curl, "== Info: %s", data);
+               break;
+       case CURLINFO_HEADER_OUT:
+               text = "=> Send header";
+               curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
+               break;
+       case CURLINFO_DATA_OUT:
+               if (trace_curl_data) {
+                       text = "=> Send data";
+                       curl_dump_data(text, (unsigned char *)data, size);
+               }
+               break;
+       case CURLINFO_SSL_DATA_OUT:
+               if (trace_curl_data) {
+                       text = "=> Send SSL data";
+                       curl_dump_data(text, (unsigned char *)data, size);
+               }
+               break;
+       case CURLINFO_HEADER_IN:
+               text = "<= Recv header";
+               curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
+               break;
+       case CURLINFO_DATA_IN:
+               if (trace_curl_data) {
+                       text = "<= Recv data";
+                       curl_dump_data(text, (unsigned char *)data, size);
+               }
+               break;
+       case CURLINFO_SSL_DATA_IN:
+               if (trace_curl_data) {
+                       text = "<= Recv SSL data";
+                       curl_dump_data(text, (unsigned char *)data, size);
+               }
+               break;
+
+       default:                /* we ignore unknown types by default */
+               return 0;
+       }
+       return 0;
+}
+
+void setup_curl_trace(CURL *handle)
+{
+       if (!trace_want(&trace_curl))
+               return;
+       curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
+       curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
+       curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
+}
+
+#ifdef CURLPROTO_HTTP
+static long get_curl_allowed_protocols(int from_user)
+{
+       long allowed_protocols = 0;
+
+       if (is_transport_allowed("http", from_user))
+               allowed_protocols |= CURLPROTO_HTTP;
+       if (is_transport_allowed("https", from_user))
+               allowed_protocols |= CURLPROTO_HTTPS;
+       if (is_transport_allowed("ftp", from_user))
+               allowed_protocols |= CURLPROTO_FTP;
+       if (is_transport_allowed("ftps", from_user))
+               allowed_protocols |= CURLPROTO_FTPS;
+
+       return allowed_protocols;
+}
+#endif
+
 static CURL *get_curl_handle(void)
 {
        CURL *result = curl_easy_init();
-       long allowed_protocols = 0;
 
        if (!result)
                die("curl_easy_init failed");
@@ -489,6 +783,22 @@ static CURL *get_curl_handle(void)
        curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 #endif
 
+#ifdef CURLGSSAPI_DELEGATION_FLAG
+       if (curl_deleg) {
+               int i;
+               for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
+                       if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
+                               curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
+                                               curl_deleg_levels[i].curl_deleg_param);
+                               break;
+                       }
+               }
+               if (i == ARRAY_SIZE(curl_deleg_levels))
+                       warning("Unknown delegation method '%s': using default",
+                               curl_deleg);
+       }
+#endif
+
        if (http_proactive_auth)
                init_curl_http_auth(result);
 
@@ -540,31 +850,31 @@ static CURL *get_curl_handle(void)
                                 curl_low_speed_time);
        }
 
-       curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
 #if LIBCURL_VERSION_NUM >= 0x071301
        curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
 #elif LIBCURL_VERSION_NUM >= 0x071101
        curl_easy_setopt(result, CURLOPT_POST301, 1);
 #endif
-#if LIBCURL_VERSION_NUM >= 0x071304
-       if (is_transport_allowed("http"))
-               allowed_protocols |= CURLPROTO_HTTP;
-       if (is_transport_allowed("https"))
-               allowed_protocols |= CURLPROTO_HTTPS;
-       if (is_transport_allowed("ftp"))
-               allowed_protocols |= CURLPROTO_FTP;
-       if (is_transport_allowed("ftps"))
-               allowed_protocols |= CURLPROTO_FTPS;
-       curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
+#ifdef CURLPROTO_HTTP
+       curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
+                        get_curl_allowed_protocols(0));
+       curl_easy_setopt(result, CURLOPT_PROTOCOLS,
+                        get_curl_allowed_protocols(-1));
 #else
-       if (transport_restrict_protocols())
-               warning("protocol restrictions not applied to curl redirects because\n"
-                       "your curl version is too old (>= 7.19.4)");
+       warning("protocol restrictions not applied to curl redirects because\n"
+               "your curl version is too old (>= 7.19.4)");
 #endif
-
        if (getenv("GIT_CURL_VERBOSE"))
-               curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
+               curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
+       setup_curl_trace(result);
+       if (getenv("GIT_TRACE_CURL_NO_DATA"))
+               trace_curl_data = 0;
+       if (getenv("GIT_REDACT_COOKIES")) {
+               string_list_split(&cookies_to_redact,
+                                 getenv("GIT_REDACT_COOKIES"), ',', -1);
+               string_list_sort(&cookies_to_redact);
+       }
 
        curl_easy_setopt(result, CURLOPT_USERAGENT,
                user_agent ? user_agent : git_user_agent());
@@ -590,7 +900,7 @@ static CURL *get_curl_handle(void)
         * precedence here, as in CURL.
         */
        if (!curl_http_proxy) {
-               if (!strcmp(http_auth.protocol, "https")) {
+               if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
                        var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
                        var_override(&curl_http_proxy, getenv("https_proxy"));
                } else {
@@ -602,8 +912,14 @@ static CURL *get_curl_handle(void)
                }
        }
 
-       if (curl_http_proxy) {
-               curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
+       if (curl_http_proxy && curl_http_proxy[0] == '\0') {
+               /*
+                * Handle case with the empty http.proxy value here to keep
+                * common code clean.
+                * NB: empty option disables proxying at all.
+                */
+               curl_easy_setopt(result, CURLOPT_PROXY, "");
+       } else if (curl_http_proxy) {
 #if LIBCURL_VERSION_NUM >= 0x071800
                if (starts_with(curl_http_proxy, "socks5h"))
                        curl_easy_setopt(result,
@@ -618,6 +934,11 @@ static CURL *get_curl_handle(void)
                        curl_easy_setopt(result,
                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
 #endif
+#if LIBCURL_VERSION_NUM >= 0x073400
+               else if (starts_with(curl_http_proxy, "https"))
+                       curl_easy_setopt(result,
+                               CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
+#endif
                if (strstr(curl_http_proxy, "://"))
                        credential_from_url(&proxy_auth, curl_http_proxy);
                else {
@@ -627,6 +948,9 @@ static CURL *get_curl_handle(void)
                        strbuf_release(&url);
                }
 
+               if (!proxy_auth.host)
+                       die("Invalid proxy URL '%s'", curl_http_proxy);
+
                curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
 #if LIBCURL_VERSION_NUM >= 0x071304
                var_override(&curl_no_proxy, getenv("NO_PROXY"));
@@ -648,6 +972,21 @@ static void set_from_env(const char **var, const char *envname)
                *var = val;
 }
 
+static void protocol_http_header(void)
+{
+       if (get_protocol_version_config() > 0) {
+               struct strbuf protocol_header = STRBUF_INIT;
+
+               strbuf_addf(&protocol_header, GIT_PROTOCOL_HEADER ": version=%d",
+                           get_protocol_version_config());
+
+
+               extra_http_headers = curl_slist_append(extra_http_headers,
+                                                      protocol_header.buf);
+               strbuf_release(&protocol_header);
+       }
+}
+
 void http_init(struct remote *remote, const char *url, int proactive_auth)
 {
        char *low_speed_limit;
@@ -678,8 +1017,12 @@ void http_init(struct remote *remote, const char *url, int proactive_auth)
        if (remote)
                var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
 
-       pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
-       no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
+       protocol_http_header();
+
+       pragma_header = curl_slist_append(http_copy_default_headers(),
+               "Pragma: no-cache");
+       no_pragma_header = curl_slist_append(http_copy_default_headers(),
+               "Pragma:");
 
 #ifdef USE_CURL_MULTI
        {
@@ -746,9 +1089,7 @@ void http_cleanup(void)
        while (slot != NULL) {
                struct active_request_slot *next = slot->next;
                if (slot->curl != NULL) {
-#ifdef USE_CURL_MULTI
-                       curl_multi_remove_handle(curlm, slot->curl);
-#endif
+                       xmulti_remove_handle(slot);
                        curl_easy_cleanup(slot->curl);
                }
                free(slot);
@@ -765,6 +1106,9 @@ void http_cleanup(void)
 #endif
        curl_global_cleanup();
 
+       curl_slist_free_all(extra_http_headers);
+       extra_http_headers = NULL;
+
        curl_slist_free_all(pragma_header);
        pragma_header = NULL;
 
@@ -778,8 +1122,7 @@ void http_cleanup(void)
 
        if (proxy_auth.password) {
                memset(proxy_auth.password, 0, strlen(proxy_auth.password));
-               free(proxy_auth.password);
-               proxy_auth.password = NULL;
+               FREE_AND_NULL(proxy_auth.password);
        }
 
        free((void *)curl_proxyuserpwd);
@@ -790,13 +1133,11 @@ void http_cleanup(void)
 
        if (cert_auth.password != NULL) {
                memset(cert_auth.password, 0, strlen(cert_auth.password));
-               free(cert_auth.password);
-               cert_auth.password = NULL;
+               FREE_AND_NULL(cert_auth.password);
        }
        ssl_cert_password_required = 0;
 
-       free(cached_accept_language);
-       cached_accept_language = NULL;
+       FREE_AND_NULL(cached_accept_language);
 }
 
 struct active_request_slot *get_active_slot(void)
@@ -864,13 +1205,23 @@ struct active_request_slot *get_active_slot(void)
        curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
        curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
 
+       /*
+        * Default following to off unless "ALWAYS" is configured; this gives
+        * callers a sane starting point, and they can tweak for individual
+        * HTTP_FOLLOW_* cases themselves.
+        */
+       if (http_follow_config == HTTP_FOLLOW_ALWAYS)
+               curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
+       else
+               curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
+
 #if LIBCURL_VERSION_NUM >= 0x070a08
        curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
 #endif
 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
        curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
 #endif
-       if (http_auth.password || curl_empty_auth)
+       if (http_auth.password || curl_empty_auth_enabled())
                init_curl_http_auth(slot->curl);
 
        return slot;
@@ -884,6 +1235,8 @@ int start_active_slot(struct active_request_slot *slot)
 
        if (curlm_result != CURLM_OK &&
            curlm_result != CURLM_CALL_MULTI_PERFORM) {
+               warning("curl_multi_add_handle failed: %s",
+                       curl_multi_strerror(curlm_result));
                active_requests--;
                slot->in_use = 0;
                return 0;
@@ -909,14 +1262,14 @@ static struct fill_chain *fill_cfg;
 
 void add_fill_function(void *data, int (*fill)(void *))
 {
-       struct fill_chain *new = xmalloc(sizeof(*new));
+       struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
        struct fill_chain **linkp = &fill_cfg;
-       new->data = data;
-       new->fill = fill;
-       new->next = NULL;
+       new_fill->data = data;
+       new_fill->fill = fill;
+       new_fill->next = NULL;
        while (*linkp)
                linkp = &(*linkp)->next;
-       *linkp = new;
+       *linkp = new_fill;
 }
 
 void fill_active_slots(void)
@@ -1023,13 +1376,13 @@ void run_active_slot(struct active_request_slot *slot)
 static void release_active_slot(struct active_request_slot *slot)
 {
        closedown_active_slot(slot);
-       if (slot->curl && curl_session_count > min_curl_sessions) {
-#ifdef USE_CURL_MULTI
-               curl_multi_remove_handle(curlm, slot->curl);
-#endif
-               curl_easy_cleanup(slot->curl);
-               slot->curl = NULL;
-               curl_session_count--;
+       if (slot->curl) {
+               xmulti_remove_handle(slot);
+               if (curl_session_count > min_curl_sessions) {
+                       curl_easy_cleanup(slot->curl);
+                       slot->curl = NULL;
+                       curl_session_count--;
+               }
        }
 #ifdef USE_CURL_MULTI
        fill_active_slots();
@@ -1087,7 +1440,7 @@ void append_remote_object_url(struct strbuf *buf, const char *url,
 
        strbuf_addf(buf, "objects/%.*s/", 2, hex);
        if (!only_two_digit_prefix)
-               strbuf_addf(buf, "%s", hex+2);
+               strbuf_addstr(buf, hex + 2);
 }
 
 char *get_remote_object_url(const char *url, const char *hex,
@@ -1104,9 +1457,12 @@ static int handle_curl_result(struct slot_results *results)
         * If we see a failing http code with CURLE_OK, we have turned off
         * FAILONERROR (to keep the server's custom error response), and should
         * translate the code into failure here.
+        *
+        * Likewise, if we see a redirect (30x code), that means we turned off
+        * redirect-following, and we should treat the result as an error.
         */
        if (results->curl_result == CURLE_OK &&
-           results->http_code >= 400) {
+           results->http_code >= 300) {
                results->curl_result = CURLE_HTTP_RETURNED_ERROR;
                /*
                 * Normally curl will already have put the "reason phrase"
@@ -1114,9 +1470,9 @@ static int handle_curl_result(struct slot_results *results)
                 * FAILONERROR it is lost, so we can give only the numeric
                 * status code.
                 */
-               snprintf(curl_errorstr, sizeof(curl_errorstr),
-                        "The requested URL returned error: %ld",
-                        results->http_code);
+               xsnprintf(curl_errorstr, sizeof(curl_errorstr),
+                         "The requested URL returned error: %ld",
+                         results->http_code);
        }
 
        if (results->curl_result == CURLE_OK) {
@@ -1133,6 +1489,10 @@ static int handle_curl_result(struct slot_results *results)
                } else {
 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
                        http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
+                       if (results->auth_avail) {
+                               http_auth_methods &= results->auth_avail;
+                               http_auth_methods_restricted = 1;
+                       }
 #endif
                        return HTTP_REAUTH;
                }
@@ -1154,8 +1514,8 @@ int run_one_slot(struct active_request_slot *slot,
 {
        slot->results = results;
        if (!start_active_slot(slot)) {
-               snprintf(curl_errorstr, sizeof(curl_errorstr),
-                        "failed to start HTTP request");
+               xsnprintf(curl_errorstr, sizeof(curl_errorstr),
+                         "failed to start HTTP request");
                return HTTP_START_FAILED;
        }
 
@@ -1163,6 +1523,16 @@ int run_one_slot(struct active_request_slot *slot,
        return handle_curl_result(results);
 }
 
+struct curl_slist *http_copy_default_headers(void)
+{
+       struct curl_slist *headers = NULL, *h;
+
+       for (h = extra_http_headers; h; h = h->next)
+               headers = curl_slist_append(headers, h->data);
+
+       return headers;
+}
+
 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
 {
        char *ptr;
@@ -1380,7 +1750,7 @@ static int http_request(const char *url,
 {
        struct active_request_slot *slot;
        struct slot_results results;
-       struct curl_slist *headers = NULL;
+       struct curl_slist *headers = http_copy_default_headers();
        struct strbuf buf = STRBUF_INIT;
        const char *accept_language;
        int ret;
@@ -1415,6 +1785,9 @@ static int http_request(const char *url,
                strbuf_addstr(&buf, " no-cache");
        if (options && options->keep_error)
                curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
+       if (options && options->initial_request &&
+           http_follow_config == HTTP_FOLLOW_INITIAL)
+               curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
 
        headers = curl_slist_append(headers, buf.buf);
 
@@ -1463,16 +1836,16 @@ static int http_request(const char *url,
  *
  * Note that this assumes a sane redirect scheme. It's entirely possible
  * in the example above to end up at a URL that does not even end in
- * "info/refs".  In such a case we simply punt, as there is not much we can
- * do (and such a scheme is unlikely to represent a real git repository,
- * which means we are likely about to abort anyway).
+ * "info/refs".  In such a case we die. There's not much we can do, such a
+ * scheme is unlikely to represent a real git repository, and failing to
+ * rewrite the base opens options for malicious redirects to do funny things.
  */
 static int update_url_from_redirect(struct strbuf *base,
                                    const char *asked,
                                    const struct strbuf *got)
 {
        const char *tail;
-       size_t tail_len;
+       size_t new_len;
 
        if (!strcmp(asked, got->buf))
                return 0;
@@ -1481,14 +1854,16 @@ static int update_url_from_redirect(struct strbuf *base,
                die("BUG: update_url_from_redirect: %s is not a superset of %s",
                    asked, base->buf);
 
-       tail_len = strlen(tail);
-
-       if (got->len < tail_len ||
-           strcmp(tail, got->buf + got->len - tail_len))
-               return 0; /* insane redirect scheme */
+       new_len = got->len;
+       if (!strip_suffix_mem(got->buf, &new_len, tail))
+               die(_("unable to update url base from redirection:\n"
+                     "  asked for: %s\n"
+                     "   redirect: %s"),
+                   asked, got->buf);
 
        strbuf_reset(base);
-       strbuf_add(base, got->buf, got->len - tail_len);
+       strbuf_add(base, got->buf, new_len);
+
        return 1;
 }
 
@@ -1498,6 +1873,9 @@ static int http_request_reauth(const char *url,
 {
        int ret = http_request(url, result, target, options);
 
+       if (ret != HTTP_OK && ret != HTTP_REAUTH)
+               return ret;
+
        if (options && options->effective_url && options->base_url) {
                if (update_url_from_redirect(options->base_url,
                                             url, options->effective_url)) {
@@ -1611,8 +1989,7 @@ static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
 
        if (http_get_file(url, tmp, NULL) != HTTP_OK) {
                error("Unable to get pack index %s", url);
-               free(tmp);
-               tmp = NULL;
+               FREE_AND_NULL(tmp);
        }
 
        free(url);
@@ -1721,7 +2098,6 @@ int finish_http_pack_request(struct http_pack_request *preq)
        char *tmp_idx;
        size_t len;
        struct child_process ip = CHILD_PROCESS_INIT;
-       const char *ip_argv[8];
 
        close_pack_index(p);
 
@@ -1737,13 +2113,9 @@ int finish_http_pack_request(struct http_pack_request *preq)
                die("BUG: pack tmpfile does not end in .pack.temp?");
        tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
 
-       ip_argv[0] = "index-pack";
-       ip_argv[1] = "-o";
-       ip_argv[2] = tmp_idx;
-       ip_argv[3] = preq->tmpfile;
-       ip_argv[4] = NULL;
-
-       ip.argv = ip_argv;
+       argv_array_push(&ip.args, "index-pack");
+       argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
+       argv_array_push(&ip.args, preq->tmpfile);
        ip.git_cmd = 1;
        ip.no_stdin = 1;
        ip.no_stdout = 1;
@@ -1827,8 +2199,19 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
        unsigned char expn[4096];
        size_t size = eltsize * nmemb;
        int posn = 0;
-       struct http_object_request *freq =
-               (struct http_object_request *)data;
+       struct http_object_request *freq = data;
+       struct active_request_slot *slot = freq->slot;
+
+       if (slot) {
+               CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
+                                               &slot->http_code);
+               if (c != CURLE_OK)
+                       die("BUG: curl_easy_getinfo for HTTP code failed: %s",
+                               curl_easy_strerror(c));
+               if (slot->http_code >= 300)
+                       return size;
+       }
+
        do {
                ssize_t retval = xwrite(freq->localfile,
                                        (char *) ptr + posn, size - posn);
@@ -1853,7 +2236,7 @@ struct http_object_request *new_http_object_request(const char *base_url,
        unsigned char *sha1)
 {
        char *hex = sha1_to_hex(sha1);
-       const char *filename;
+       struct strbuf filename = STRBUF_INIT;
        char prevfile[PATH_MAX];
        int prevlocal;
        char prev_buf[PREV_BUF_SIZE];
@@ -1865,14 +2248,15 @@ struct http_object_request *new_http_object_request(const char *base_url,
        hashcpy(freq->sha1, sha1);
        freq->localfile = -1;
 
-       filename = sha1_file_name(sha1);
+       sha1_file_name(&filename, sha1);
        snprintf(freq->tmpfile, sizeof(freq->tmpfile),
-                "%s.temp", filename);
+                "%s.temp", filename.buf);
 
-       snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
+       snprintf(prevfile, sizeof(prevfile), "%s.prev", filename.buf);
        unlink_or_warn(prevfile);
        rename(freq->tmpfile, prevfile);
        unlink_or_warn(freq->tmpfile);
+       strbuf_release(&filename);
 
        if (freq->localfile != -1)
                error("fd leakage in start: %d", freq->localfile);
@@ -1894,8 +2278,7 @@ struct http_object_request *new_http_object_request(const char *base_url,
        }
 
        if (freq->localfile < 0) {
-               error("Couldn't create temporary file %s: %s",
-                     freq->tmpfile, strerror(errno));
+               error_errno("Couldn't create temporary file %s", freq->tmpfile);
                goto abort;
        }
 
@@ -1940,8 +2323,8 @@ struct http_object_request *new_http_object_request(const char *base_url,
                        prev_posn = 0;
                        lseek(freq->localfile, 0, SEEK_SET);
                        if (ftruncate(freq->localfile, 0) < 0) {
-                               error("Couldn't truncate temporary file %s: %s",
-                                         freq->tmpfile, strerror(errno));
+                               error_errno("Couldn't truncate temporary file %s",
+                                           freq->tmpfile);
                                goto abort;
                        }
                }
@@ -1950,6 +2333,7 @@ struct http_object_request *new_http_object_request(const char *base_url,
        freq->slot = get_active_slot();
 
        curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
+       curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
        curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
        curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
        curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
@@ -1987,6 +2371,7 @@ void process_http_object_request(struct http_object_request *freq)
 int finish_http_object_request(struct http_object_request *freq)
 {
        struct stat st;
+       struct strbuf filename = STRBUF_INIT;
 
        close(freq->localfile);
        freq->localfile = -1;
@@ -2012,8 +2397,10 @@ int finish_http_object_request(struct http_object_request *freq)
                unlink_or_warn(freq->tmpfile);
                return -1;
        }
-       freq->rename =
-               finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
+
+       sha1_file_name(&filename, freq->sha1);
+       freq->rename = finalize_object_file(freq->tmpfile, filename.buf);
+       strbuf_release(&filename);
 
        return freq->rename;
 }
@@ -2032,8 +2419,7 @@ void release_http_object_request(struct http_object_request *freq)
                freq->localfile = -1;
        }
        if (freq->url != NULL) {
-               free(freq->url);
-               freq->url = NULL;
+               FREE_AND_NULL(freq->url);
        }
        if (freq->slot != NULL) {
                freq->slot->callback_func = NULL;