Merge branch 'jk/config-include'
[git] / http.c
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "pack.h"
4 #include "sideband.h"
5 #include "run-command.h"
6 #include "url.h"
7 #include "urlmatch.h"
8 #include "credential.h"
9 #include "version.h"
10 #include "pkt-line.h"
11 #include "gettext.h"
12 #include "transport.h"
13
14 int active_requests;
15 int http_is_verbose;
16 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
17
18 #if LIBCURL_VERSION_NUM >= 0x070a06
19 #define LIBCURL_CAN_HANDLE_AUTH_ANY
20 #endif
21
22 static int min_curl_sessions = 1;
23 static int curl_session_count;
24 #ifdef USE_CURL_MULTI
25 static int max_requests = -1;
26 static CURLM *curlm;
27 #endif
28 #ifndef NO_CURL_EASY_DUPHANDLE
29 static CURL *curl_default;
30 #endif
31
32 #define PREV_BUF_SIZE 4096
33
34 char curl_errorstr[CURL_ERROR_SIZE];
35
36 static int curl_ssl_verify = -1;
37 static int curl_ssl_try;
38 static const char *ssl_cert;
39 static const char *ssl_cipherlist;
40 static const char *ssl_version;
41 static struct {
42         const char *name;
43         long ssl_version;
44 } sslversions[] = {
45         { "sslv2", CURL_SSLVERSION_SSLv2 },
46         { "sslv3", CURL_SSLVERSION_SSLv3 },
47         { "tlsv1", CURL_SSLVERSION_TLSv1 },
48 #if LIBCURL_VERSION_NUM >= 0x072200
49         { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
50         { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
51         { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
52 #endif
53 };
54 #if LIBCURL_VERSION_NUM >= 0x070903
55 static const char *ssl_key;
56 #endif
57 #if LIBCURL_VERSION_NUM >= 0x070908
58 static const char *ssl_capath;
59 #endif
60 static const char *ssl_cainfo;
61 static long curl_low_speed_limit = -1;
62 static long curl_low_speed_time = -1;
63 static int curl_ftp_no_epsv;
64 static const char *curl_http_proxy;
65 static const char *http_proxy_authmethod;
66 static struct {
67         const char *name;
68         long curlauth_param;
69 } proxy_authmethods[] = {
70         { "basic", CURLAUTH_BASIC },
71         { "digest", CURLAUTH_DIGEST },
72         { "negotiate", CURLAUTH_GSSNEGOTIATE },
73         { "ntlm", CURLAUTH_NTLM },
74 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
75         { "anyauth", CURLAUTH_ANY },
76 #endif
77         /*
78          * CURLAUTH_DIGEST_IE has no corresponding command-line option in
79          * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
80          * here, too
81          */
82 };
83 static struct credential proxy_auth = CREDENTIAL_INIT;
84 static const char *curl_proxyuserpwd;
85 static const char *curl_cookie_file;
86 static int curl_save_cookies;
87 struct credential http_auth = CREDENTIAL_INIT;
88 static int http_proactive_auth;
89 static const char *user_agent;
90
91 #if LIBCURL_VERSION_NUM >= 0x071700
92 /* Use CURLOPT_KEYPASSWD as is */
93 #elif LIBCURL_VERSION_NUM >= 0x070903
94 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
95 #else
96 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
97 #endif
98
99 static struct credential cert_auth = CREDENTIAL_INIT;
100 static int ssl_cert_password_required;
101 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
102 static unsigned long http_auth_methods = CURLAUTH_ANY;
103 #endif
104
105 static struct curl_slist *pragma_header;
106 static struct curl_slist *no_pragma_header;
107
108 static struct active_request_slot *active_queue_head;
109
110 static char *cached_accept_language;
111
112 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
113 {
114         size_t size = eltsize * nmemb;
115         struct buffer *buffer = buffer_;
116
117         if (size > buffer->buf.len - buffer->posn)
118                 size = buffer->buf.len - buffer->posn;
119         memcpy(ptr, buffer->buf.buf + buffer->posn, size);
120         buffer->posn += size;
121
122         return size;
123 }
124
125 #ifndef NO_CURL_IOCTL
126 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
127 {
128         struct buffer *buffer = clientp;
129
130         switch (cmd) {
131         case CURLIOCMD_NOP:
132                 return CURLIOE_OK;
133
134         case CURLIOCMD_RESTARTREAD:
135                 buffer->posn = 0;
136                 return CURLIOE_OK;
137
138         default:
139                 return CURLIOE_UNKNOWNCMD;
140         }
141 }
142 #endif
143
144 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
145 {
146         size_t size = eltsize * nmemb;
147         struct strbuf *buffer = buffer_;
148
149         strbuf_add(buffer, ptr, size);
150         return size;
151 }
152
153 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
154 {
155         return eltsize * nmemb;
156 }
157
158 static void closedown_active_slot(struct active_request_slot *slot)
159 {
160         active_requests--;
161         slot->in_use = 0;
162 }
163
164 static void finish_active_slot(struct active_request_slot *slot)
165 {
166         closedown_active_slot(slot);
167         curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
168
169         if (slot->finished != NULL)
170                 (*slot->finished) = 1;
171
172         /* Store slot results so they can be read after the slot is reused */
173         if (slot->results != NULL) {
174                 slot->results->curl_result = slot->curl_result;
175                 slot->results->http_code = slot->http_code;
176 #if LIBCURL_VERSION_NUM >= 0x070a08
177                 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
178                                   &slot->results->auth_avail);
179 #else
180                 slot->results->auth_avail = 0;
181 #endif
182
183                 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
184                         &slot->results->http_connectcode);
185         }
186
187         /* Run callback if appropriate */
188         if (slot->callback_func != NULL)
189                 slot->callback_func(slot->callback_data);
190 }
191
192 #ifdef USE_CURL_MULTI
193 static void process_curl_messages(void)
194 {
195         int num_messages;
196         struct active_request_slot *slot;
197         CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
198
199         while (curl_message != NULL) {
200                 if (curl_message->msg == CURLMSG_DONE) {
201                         int curl_result = curl_message->data.result;
202                         slot = active_queue_head;
203                         while (slot != NULL &&
204                                slot->curl != curl_message->easy_handle)
205                                 slot = slot->next;
206                         if (slot != NULL) {
207                                 curl_multi_remove_handle(curlm, slot->curl);
208                                 slot->curl_result = curl_result;
209                                 finish_active_slot(slot);
210                         } else {
211                                 fprintf(stderr, "Received DONE message for unknown request!\n");
212                         }
213                 } else {
214                         fprintf(stderr, "Unknown CURL message received: %d\n",
215                                 (int)curl_message->msg);
216                 }
217                 curl_message = curl_multi_info_read(curlm, &num_messages);
218         }
219 }
220 #endif
221
222 static int http_options(const char *var, const char *value, void *cb)
223 {
224         if (!strcmp("http.sslverify", var)) {
225                 curl_ssl_verify = git_config_bool(var, value);
226                 return 0;
227         }
228         if (!strcmp("http.sslcipherlist", var))
229                 return git_config_string(&ssl_cipherlist, var, value);
230         if (!strcmp("http.sslversion", var))
231                 return git_config_string(&ssl_version, var, value);
232         if (!strcmp("http.sslcert", var))
233                 return git_config_string(&ssl_cert, var, value);
234 #if LIBCURL_VERSION_NUM >= 0x070903
235         if (!strcmp("http.sslkey", var))
236                 return git_config_string(&ssl_key, var, value);
237 #endif
238 #if LIBCURL_VERSION_NUM >= 0x070908
239         if (!strcmp("http.sslcapath", var))
240                 return git_config_pathname(&ssl_capath, var, value);
241 #endif
242         if (!strcmp("http.sslcainfo", var))
243                 return git_config_pathname(&ssl_cainfo, var, value);
244         if (!strcmp("http.sslcertpasswordprotected", var)) {
245                 ssl_cert_password_required = git_config_bool(var, value);
246                 return 0;
247         }
248         if (!strcmp("http.ssltry", var)) {
249                 curl_ssl_try = git_config_bool(var, value);
250                 return 0;
251         }
252         if (!strcmp("http.minsessions", var)) {
253                 min_curl_sessions = git_config_int(var, value);
254 #ifndef USE_CURL_MULTI
255                 if (min_curl_sessions > 1)
256                         min_curl_sessions = 1;
257 #endif
258                 return 0;
259         }
260 #ifdef USE_CURL_MULTI
261         if (!strcmp("http.maxrequests", var)) {
262                 max_requests = git_config_int(var, value);
263                 return 0;
264         }
265 #endif
266         if (!strcmp("http.lowspeedlimit", var)) {
267                 curl_low_speed_limit = (long)git_config_int(var, value);
268                 return 0;
269         }
270         if (!strcmp("http.lowspeedtime", var)) {
271                 curl_low_speed_time = (long)git_config_int(var, value);
272                 return 0;
273         }
274
275         if (!strcmp("http.noepsv", var)) {
276                 curl_ftp_no_epsv = git_config_bool(var, value);
277                 return 0;
278         }
279         if (!strcmp("http.proxy", var))
280                 return git_config_string(&curl_http_proxy, var, value);
281
282         if (!strcmp("http.proxyauthmethod", var))
283                 return git_config_string(&http_proxy_authmethod, var, value);
284
285         if (!strcmp("http.cookiefile", var))
286                 return git_config_string(&curl_cookie_file, var, value);
287         if (!strcmp("http.savecookies", var)) {
288                 curl_save_cookies = git_config_bool(var, value);
289                 return 0;
290         }
291
292         if (!strcmp("http.postbuffer", var)) {
293                 http_post_buffer = git_config_int(var, value);
294                 if (http_post_buffer < LARGE_PACKET_MAX)
295                         http_post_buffer = LARGE_PACKET_MAX;
296                 return 0;
297         }
298
299         if (!strcmp("http.useragent", var))
300                 return git_config_string(&user_agent, var, value);
301
302         /* Fall back on the default ones */
303         return git_default_config(var, value, cb);
304 }
305
306 static void init_curl_http_auth(CURL *result)
307 {
308         if (!http_auth.username)
309                 return;
310
311         credential_fill(&http_auth);
312
313 #if LIBCURL_VERSION_NUM >= 0x071301
314         curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
315         curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
316 #else
317         {
318                 static struct strbuf up = STRBUF_INIT;
319                 /*
320                  * Note that we assume we only ever have a single set of
321                  * credentials in a given program run, so we do not have
322                  * to worry about updating this buffer, only setting its
323                  * initial value.
324                  */
325                 if (!up.len)
326                         strbuf_addf(&up, "%s:%s",
327                                 http_auth.username, http_auth.password);
328                 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
329         }
330 #endif
331 }
332
333 /* *var must be free-able */
334 static void var_override(const char **var, char *value)
335 {
336         if (value) {
337                 free((void *)*var);
338                 *var = xstrdup(value);
339         }
340 }
341
342 static void set_proxyauth_name_password(CURL *result)
343 {
344 #if LIBCURL_VERSION_NUM >= 0x071301
345                 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
346                         proxy_auth.username);
347                 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
348                         proxy_auth.password);
349 #else
350                 struct strbuf s = STRBUF_INIT;
351
352                 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
353                 strbuf_addch(&s, ':');
354                 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
355                 curl_proxyuserpwd = strbuf_detach(&s, NULL);
356                 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
357 #endif
358 }
359
360 static void init_curl_proxy_auth(CURL *result)
361 {
362         if (proxy_auth.username) {
363                 if (!proxy_auth.password)
364                         credential_fill(&proxy_auth);
365                 set_proxyauth_name_password(result);
366         }
367
368         var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
369
370 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
371         if (http_proxy_authmethod) {
372                 int i;
373                 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
374                         if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
375                                 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
376                                                 proxy_authmethods[i].curlauth_param);
377                                 break;
378                         }
379                 }
380                 if (i == ARRAY_SIZE(proxy_authmethods)) {
381                         warning("unsupported proxy authentication method %s: using anyauth",
382                                         http_proxy_authmethod);
383                         curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
384                 }
385         }
386         else
387                 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
388 #endif
389 }
390
391 static int has_cert_password(void)
392 {
393         if (ssl_cert == NULL || ssl_cert_password_required != 1)
394                 return 0;
395         if (!cert_auth.password) {
396                 cert_auth.protocol = xstrdup("cert");
397                 cert_auth.username = xstrdup("");
398                 cert_auth.path = xstrdup(ssl_cert);
399                 credential_fill(&cert_auth);
400         }
401         return 1;
402 }
403
404 #if LIBCURL_VERSION_NUM >= 0x071900
405 static void set_curl_keepalive(CURL *c)
406 {
407         curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
408 }
409
410 #elif LIBCURL_VERSION_NUM >= 0x071000
411 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
412 {
413         int ka = 1;
414         int rc;
415         socklen_t len = (socklen_t)sizeof(ka);
416
417         if (type != CURLSOCKTYPE_IPCXN)
418                 return 0;
419
420         rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
421         if (rc < 0)
422                 warning("unable to set SO_KEEPALIVE on socket %s",
423                         strerror(errno));
424
425         return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
426 }
427
428 static void set_curl_keepalive(CURL *c)
429 {
430         curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
431 }
432
433 #else
434 static void set_curl_keepalive(CURL *c)
435 {
436         /* not supported on older curl versions */
437 }
438 #endif
439
440 static CURL *get_curl_handle(void)
441 {
442         CURL *result = curl_easy_init();
443         long allowed_protocols = 0;
444
445         if (!result)
446                 die("curl_easy_init failed");
447
448         if (!curl_ssl_verify) {
449                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
450                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
451         } else {
452                 /* Verify authenticity of the peer's certificate */
453                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
454                 /* The name in the cert must match whom we tried to connect */
455                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
456         }
457
458 #if LIBCURL_VERSION_NUM >= 0x070907
459         curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
460 #endif
461 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
462         curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
463 #endif
464
465         if (http_proactive_auth)
466                 init_curl_http_auth(result);
467
468         if (getenv("GIT_SSL_VERSION"))
469                 ssl_version = getenv("GIT_SSL_VERSION");
470         if (ssl_version && *ssl_version) {
471                 int i;
472                 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
473                         if (!strcmp(ssl_version, sslversions[i].name)) {
474                                 curl_easy_setopt(result, CURLOPT_SSLVERSION,
475                                                  sslversions[i].ssl_version);
476                                 break;
477                         }
478                 }
479                 if (i == ARRAY_SIZE(sslversions))
480                         warning("unsupported ssl version %s: using default",
481                                 ssl_version);
482         }
483
484         if (getenv("GIT_SSL_CIPHER_LIST"))
485                 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
486         if (ssl_cipherlist != NULL && *ssl_cipherlist)
487                 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
488                                 ssl_cipherlist);
489
490         if (ssl_cert != NULL)
491                 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
492         if (has_cert_password())
493                 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
494 #if LIBCURL_VERSION_NUM >= 0x070903
495         if (ssl_key != NULL)
496                 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
497 #endif
498 #if LIBCURL_VERSION_NUM >= 0x070908
499         if (ssl_capath != NULL)
500                 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
501 #endif
502         if (ssl_cainfo != NULL)
503                 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
504
505         if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
506                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
507                                  curl_low_speed_limit);
508                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
509                                  curl_low_speed_time);
510         }
511
512         curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
513         curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
514 #if LIBCURL_VERSION_NUM >= 0x071301
515         curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
516 #elif LIBCURL_VERSION_NUM >= 0x071101
517         curl_easy_setopt(result, CURLOPT_POST301, 1);
518 #endif
519 #if LIBCURL_VERSION_NUM >= 0x071304
520         if (is_transport_allowed("http"))
521                 allowed_protocols |= CURLPROTO_HTTP;
522         if (is_transport_allowed("https"))
523                 allowed_protocols |= CURLPROTO_HTTPS;
524         if (is_transport_allowed("ftp"))
525                 allowed_protocols |= CURLPROTO_FTP;
526         if (is_transport_allowed("ftps"))
527                 allowed_protocols |= CURLPROTO_FTPS;
528         curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
529 #else
530         if (transport_restrict_protocols())
531                 warning("protocol restrictions not applied to curl redirects because\n"
532                         "your curl version is too old (>= 7.19.4)");
533 #endif
534
535         if (getenv("GIT_CURL_VERBOSE"))
536                 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
537
538         curl_easy_setopt(result, CURLOPT_USERAGENT,
539                 user_agent ? user_agent : git_user_agent());
540
541         if (curl_ftp_no_epsv)
542                 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
543
544 #ifdef CURLOPT_USE_SSL
545         if (curl_ssl_try)
546                 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
547 #endif
548
549         /*
550          * CURL also examines these variables as a fallback; but we need to query
551          * them here in order to decide whether to prompt for missing password (cf.
552          * init_curl_proxy_auth()).
553          *
554          * Unlike many other common environment variables, these are historically
555          * lowercase only. It appears that CURL did not know this and implemented
556          * only uppercase variants, which was later corrected to take both - with
557          * the exception of http_proxy, which is lowercase only also in CURL. As
558          * the lowercase versions are the historical quasi-standard, they take
559          * precedence here, as in CURL.
560          */
561         if (!curl_http_proxy) {
562                 if (!strcmp(http_auth.protocol, "https")) {
563                         var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
564                         var_override(&curl_http_proxy, getenv("https_proxy"));
565                 } else {
566                         var_override(&curl_http_proxy, getenv("http_proxy"));
567                 }
568                 if (!curl_http_proxy) {
569                         var_override(&curl_http_proxy, getenv("ALL_PROXY"));
570                         var_override(&curl_http_proxy, getenv("all_proxy"));
571                 }
572         }
573
574         if (curl_http_proxy) {
575                 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
576 #if LIBCURL_VERSION_NUM >= 0x071800
577                 if (starts_with(curl_http_proxy, "socks5"))
578                         curl_easy_setopt(result,
579                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
580                 else if (starts_with(curl_http_proxy, "socks4a"))
581                         curl_easy_setopt(result,
582                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
583                 else if (starts_with(curl_http_proxy, "socks"))
584                         curl_easy_setopt(result,
585                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
586 #endif
587                 if (strstr(curl_http_proxy, "://"))
588                         credential_from_url(&proxy_auth, curl_http_proxy);
589                 else {
590                         struct strbuf url = STRBUF_INIT;
591                         strbuf_addf(&url, "http://%s", curl_http_proxy);
592                         credential_from_url(&proxy_auth, url.buf);
593                         strbuf_release(&url);
594                 }
595
596                 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
597         }
598         init_curl_proxy_auth(result);
599
600         set_curl_keepalive(result);
601
602         return result;
603 }
604
605 static void set_from_env(const char **var, const char *envname)
606 {
607         const char *val = getenv(envname);
608         if (val)
609                 *var = val;
610 }
611
612 void http_init(struct remote *remote, const char *url, int proactive_auth)
613 {
614         char *low_speed_limit;
615         char *low_speed_time;
616         char *normalized_url;
617         struct urlmatch_config config = { STRING_LIST_INIT_DUP };
618
619         config.section = "http";
620         config.key = NULL;
621         config.collect_fn = http_options;
622         config.cascade_fn = git_default_config;
623         config.cb = NULL;
624
625         http_is_verbose = 0;
626         normalized_url = url_normalize(url, &config.url);
627
628         git_config(urlmatch_config_entry, &config);
629         free(normalized_url);
630
631         if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
632                 die("curl_global_init failed");
633
634         http_proactive_auth = proactive_auth;
635
636         if (remote && remote->http_proxy)
637                 curl_http_proxy = xstrdup(remote->http_proxy);
638
639         if (remote)
640                 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
641
642         pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
643         no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
644
645 #ifdef USE_CURL_MULTI
646         {
647                 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
648                 if (http_max_requests != NULL)
649                         max_requests = atoi(http_max_requests);
650         }
651
652         curlm = curl_multi_init();
653         if (!curlm)
654                 die("curl_multi_init failed");
655 #endif
656
657         if (getenv("GIT_SSL_NO_VERIFY"))
658                 curl_ssl_verify = 0;
659
660         set_from_env(&ssl_cert, "GIT_SSL_CERT");
661 #if LIBCURL_VERSION_NUM >= 0x070903
662         set_from_env(&ssl_key, "GIT_SSL_KEY");
663 #endif
664 #if LIBCURL_VERSION_NUM >= 0x070908
665         set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
666 #endif
667         set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
668
669         set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
670
671         low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
672         if (low_speed_limit != NULL)
673                 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
674         low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
675         if (low_speed_time != NULL)
676                 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
677
678         if (curl_ssl_verify == -1)
679                 curl_ssl_verify = 1;
680
681         curl_session_count = 0;
682 #ifdef USE_CURL_MULTI
683         if (max_requests < 1)
684                 max_requests = DEFAULT_MAX_REQUESTS;
685 #endif
686
687         if (getenv("GIT_CURL_FTP_NO_EPSV"))
688                 curl_ftp_no_epsv = 1;
689
690         if (url) {
691                 credential_from_url(&http_auth, url);
692                 if (!ssl_cert_password_required &&
693                     getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
694                     starts_with(url, "https://"))
695                         ssl_cert_password_required = 1;
696         }
697
698 #ifndef NO_CURL_EASY_DUPHANDLE
699         curl_default = get_curl_handle();
700 #endif
701 }
702
703 void http_cleanup(void)
704 {
705         struct active_request_slot *slot = active_queue_head;
706
707         while (slot != NULL) {
708                 struct active_request_slot *next = slot->next;
709                 if (slot->curl != NULL) {
710 #ifdef USE_CURL_MULTI
711                         curl_multi_remove_handle(curlm, slot->curl);
712 #endif
713                         curl_easy_cleanup(slot->curl);
714                 }
715                 free(slot);
716                 slot = next;
717         }
718         active_queue_head = NULL;
719
720 #ifndef NO_CURL_EASY_DUPHANDLE
721         curl_easy_cleanup(curl_default);
722 #endif
723
724 #ifdef USE_CURL_MULTI
725         curl_multi_cleanup(curlm);
726 #endif
727         curl_global_cleanup();
728
729         curl_slist_free_all(pragma_header);
730         pragma_header = NULL;
731
732         curl_slist_free_all(no_pragma_header);
733         no_pragma_header = NULL;
734
735         if (curl_http_proxy) {
736                 free((void *)curl_http_proxy);
737                 curl_http_proxy = NULL;
738         }
739
740         if (proxy_auth.password) {
741                 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
742                 free(proxy_auth.password);
743                 proxy_auth.password = NULL;
744         }
745
746         free((void *)curl_proxyuserpwd);
747         curl_proxyuserpwd = NULL;
748
749         free((void *)http_proxy_authmethod);
750         http_proxy_authmethod = NULL;
751
752         if (cert_auth.password != NULL) {
753                 memset(cert_auth.password, 0, strlen(cert_auth.password));
754                 free(cert_auth.password);
755                 cert_auth.password = NULL;
756         }
757         ssl_cert_password_required = 0;
758
759         free(cached_accept_language);
760         cached_accept_language = NULL;
761 }
762
763 struct active_request_slot *get_active_slot(void)
764 {
765         struct active_request_slot *slot = active_queue_head;
766         struct active_request_slot *newslot;
767
768 #ifdef USE_CURL_MULTI
769         int num_transfers;
770
771         /* Wait for a slot to open up if the queue is full */
772         while (active_requests >= max_requests) {
773                 curl_multi_perform(curlm, &num_transfers);
774                 if (num_transfers < active_requests)
775                         process_curl_messages();
776         }
777 #endif
778
779         while (slot != NULL && slot->in_use)
780                 slot = slot->next;
781
782         if (slot == NULL) {
783                 newslot = xmalloc(sizeof(*newslot));
784                 newslot->curl = NULL;
785                 newslot->in_use = 0;
786                 newslot->next = NULL;
787
788                 slot = active_queue_head;
789                 if (slot == NULL) {
790                         active_queue_head = newslot;
791                 } else {
792                         while (slot->next != NULL)
793                                 slot = slot->next;
794                         slot->next = newslot;
795                 }
796                 slot = newslot;
797         }
798
799         if (slot->curl == NULL) {
800 #ifdef NO_CURL_EASY_DUPHANDLE
801                 slot->curl = get_curl_handle();
802 #else
803                 slot->curl = curl_easy_duphandle(curl_default);
804 #endif
805                 curl_session_count++;
806         }
807
808         active_requests++;
809         slot->in_use = 1;
810         slot->results = NULL;
811         slot->finished = NULL;
812         slot->callback_data = NULL;
813         slot->callback_func = NULL;
814         curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
815         if (curl_save_cookies)
816                 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
817         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
818         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
819         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
820         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
821         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
822         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
823         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
824         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
825         curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
826         curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
827 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
828         curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
829 #endif
830         if (http_auth.password)
831                 init_curl_http_auth(slot->curl);
832
833         return slot;
834 }
835
836 int start_active_slot(struct active_request_slot *slot)
837 {
838 #ifdef USE_CURL_MULTI
839         CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
840         int num_transfers;
841
842         if (curlm_result != CURLM_OK &&
843             curlm_result != CURLM_CALL_MULTI_PERFORM) {
844                 active_requests--;
845                 slot->in_use = 0;
846                 return 0;
847         }
848
849         /*
850          * We know there must be something to do, since we just added
851          * something.
852          */
853         curl_multi_perform(curlm, &num_transfers);
854 #endif
855         return 1;
856 }
857
858 #ifdef USE_CURL_MULTI
859 struct fill_chain {
860         void *data;
861         int (*fill)(void *);
862         struct fill_chain *next;
863 };
864
865 static struct fill_chain *fill_cfg;
866
867 void add_fill_function(void *data, int (*fill)(void *))
868 {
869         struct fill_chain *new = xmalloc(sizeof(*new));
870         struct fill_chain **linkp = &fill_cfg;
871         new->data = data;
872         new->fill = fill;
873         new->next = NULL;
874         while (*linkp)
875                 linkp = &(*linkp)->next;
876         *linkp = new;
877 }
878
879 void fill_active_slots(void)
880 {
881         struct active_request_slot *slot = active_queue_head;
882
883         while (active_requests < max_requests) {
884                 struct fill_chain *fill;
885                 for (fill = fill_cfg; fill; fill = fill->next)
886                         if (fill->fill(fill->data))
887                                 break;
888
889                 if (!fill)
890                         break;
891         }
892
893         while (slot != NULL) {
894                 if (!slot->in_use && slot->curl != NULL
895                         && curl_session_count > min_curl_sessions) {
896                         curl_easy_cleanup(slot->curl);
897                         slot->curl = NULL;
898                         curl_session_count--;
899                 }
900                 slot = slot->next;
901         }
902 }
903
904 void step_active_slots(void)
905 {
906         int num_transfers;
907         CURLMcode curlm_result;
908
909         do {
910                 curlm_result = curl_multi_perform(curlm, &num_transfers);
911         } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
912         if (num_transfers < active_requests) {
913                 process_curl_messages();
914                 fill_active_slots();
915         }
916 }
917 #endif
918
919 void run_active_slot(struct active_request_slot *slot)
920 {
921 #ifdef USE_CURL_MULTI
922         fd_set readfds;
923         fd_set writefds;
924         fd_set excfds;
925         int max_fd;
926         struct timeval select_timeout;
927         int finished = 0;
928
929         slot->finished = &finished;
930         while (!finished) {
931                 step_active_slots();
932
933                 if (slot->in_use) {
934 #if LIBCURL_VERSION_NUM >= 0x070f04
935                         long curl_timeout;
936                         curl_multi_timeout(curlm, &curl_timeout);
937                         if (curl_timeout == 0) {
938                                 continue;
939                         } else if (curl_timeout == -1) {
940                                 select_timeout.tv_sec  = 0;
941                                 select_timeout.tv_usec = 50000;
942                         } else {
943                                 select_timeout.tv_sec  =  curl_timeout / 1000;
944                                 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
945                         }
946 #else
947                         select_timeout.tv_sec  = 0;
948                         select_timeout.tv_usec = 50000;
949 #endif
950
951                         max_fd = -1;
952                         FD_ZERO(&readfds);
953                         FD_ZERO(&writefds);
954                         FD_ZERO(&excfds);
955                         curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
956
957                         /*
958                          * It can happen that curl_multi_timeout returns a pathologically
959                          * long timeout when curl_multi_fdset returns no file descriptors
960                          * to read.  See commit message for more details.
961                          */
962                         if (max_fd < 0 &&
963                             (select_timeout.tv_sec > 0 ||
964                              select_timeout.tv_usec > 50000)) {
965                                 select_timeout.tv_sec  = 0;
966                                 select_timeout.tv_usec = 50000;
967                         }
968
969                         select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
970                 }
971         }
972 #else
973         while (slot->in_use) {
974                 slot->curl_result = curl_easy_perform(slot->curl);
975                 finish_active_slot(slot);
976         }
977 #endif
978 }
979
980 static void release_active_slot(struct active_request_slot *slot)
981 {
982         closedown_active_slot(slot);
983         if (slot->curl && curl_session_count > min_curl_sessions) {
984 #ifdef USE_CURL_MULTI
985                 curl_multi_remove_handle(curlm, slot->curl);
986 #endif
987                 curl_easy_cleanup(slot->curl);
988                 slot->curl = NULL;
989                 curl_session_count--;
990         }
991 #ifdef USE_CURL_MULTI
992         fill_active_slots();
993 #endif
994 }
995
996 void finish_all_active_slots(void)
997 {
998         struct active_request_slot *slot = active_queue_head;
999
1000         while (slot != NULL)
1001                 if (slot->in_use) {
1002                         run_active_slot(slot);
1003                         slot = active_queue_head;
1004                 } else {
1005                         slot = slot->next;
1006                 }
1007 }
1008
1009 /* Helpers for modifying and creating URLs */
1010 static inline int needs_quote(int ch)
1011 {
1012         if (((ch >= 'A') && (ch <= 'Z'))
1013                         || ((ch >= 'a') && (ch <= 'z'))
1014                         || ((ch >= '0') && (ch <= '9'))
1015                         || (ch == '/')
1016                         || (ch == '-')
1017                         || (ch == '.'))
1018                 return 0;
1019         return 1;
1020 }
1021
1022 static char *quote_ref_url(const char *base, const char *ref)
1023 {
1024         struct strbuf buf = STRBUF_INIT;
1025         const char *cp;
1026         int ch;
1027
1028         end_url_with_slash(&buf, base);
1029
1030         for (cp = ref; (ch = *cp) != 0; cp++)
1031                 if (needs_quote(ch))
1032                         strbuf_addf(&buf, "%%%02x", ch);
1033                 else
1034                         strbuf_addch(&buf, *cp);
1035
1036         return strbuf_detach(&buf, NULL);
1037 }
1038
1039 void append_remote_object_url(struct strbuf *buf, const char *url,
1040                               const char *hex,
1041                               int only_two_digit_prefix)
1042 {
1043         end_url_with_slash(buf, url);
1044
1045         strbuf_addf(buf, "objects/%.*s/", 2, hex);
1046         if (!only_two_digit_prefix)
1047                 strbuf_addf(buf, "%s", hex+2);
1048 }
1049
1050 char *get_remote_object_url(const char *url, const char *hex,
1051                             int only_two_digit_prefix)
1052 {
1053         struct strbuf buf = STRBUF_INIT;
1054         append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1055         return strbuf_detach(&buf, NULL);
1056 }
1057
1058 static int handle_curl_result(struct slot_results *results)
1059 {
1060         /*
1061          * If we see a failing http code with CURLE_OK, we have turned off
1062          * FAILONERROR (to keep the server's custom error response), and should
1063          * translate the code into failure here.
1064          */
1065         if (results->curl_result == CURLE_OK &&
1066             results->http_code >= 400) {
1067                 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1068                 /*
1069                  * Normally curl will already have put the "reason phrase"
1070                  * from the server into curl_errorstr; unfortunately without
1071                  * FAILONERROR it is lost, so we can give only the numeric
1072                  * status code.
1073                  */
1074                 snprintf(curl_errorstr, sizeof(curl_errorstr),
1075                          "The requested URL returned error: %ld",
1076                          results->http_code);
1077         }
1078
1079         if (results->curl_result == CURLE_OK) {
1080                 credential_approve(&http_auth);
1081                 if (proxy_auth.password)
1082                         credential_approve(&proxy_auth);
1083                 return HTTP_OK;
1084         } else if (missing_target(results))
1085                 return HTTP_MISSING_TARGET;
1086         else if (results->http_code == 401) {
1087                 if (http_auth.username && http_auth.password) {
1088                         credential_reject(&http_auth);
1089                         return HTTP_NOAUTH;
1090                 } else {
1091 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1092                         http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1093 #endif
1094                         return HTTP_REAUTH;
1095                 }
1096         } else {
1097                 if (results->http_connectcode == 407)
1098                         credential_reject(&proxy_auth);
1099 #if LIBCURL_VERSION_NUM >= 0x070c00
1100                 if (!curl_errorstr[0])
1101                         strlcpy(curl_errorstr,
1102                                 curl_easy_strerror(results->curl_result),
1103                                 sizeof(curl_errorstr));
1104 #endif
1105                 return HTTP_ERROR;
1106         }
1107 }
1108
1109 int run_one_slot(struct active_request_slot *slot,
1110                  struct slot_results *results)
1111 {
1112         slot->results = results;
1113         if (!start_active_slot(slot)) {
1114                 snprintf(curl_errorstr, sizeof(curl_errorstr),
1115                          "failed to start HTTP request");
1116                 return HTTP_START_FAILED;
1117         }
1118
1119         run_active_slot(slot);
1120         return handle_curl_result(results);
1121 }
1122
1123 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1124 {
1125         char *ptr;
1126         CURLcode ret;
1127
1128         strbuf_reset(buf);
1129         ret = curl_easy_getinfo(curl, info, &ptr);
1130         if (!ret && ptr)
1131                 strbuf_addstr(buf, ptr);
1132         return ret;
1133 }
1134
1135 /*
1136  * Check for and extract a content-type parameter. "raw"
1137  * should be positioned at the start of the potential
1138  * parameter, with any whitespace already removed.
1139  *
1140  * "name" is the name of the parameter. The value is appended
1141  * to "out".
1142  */
1143 static int extract_param(const char *raw, const char *name,
1144                          struct strbuf *out)
1145 {
1146         size_t len = strlen(name);
1147
1148         if (strncasecmp(raw, name, len))
1149                 return -1;
1150         raw += len;
1151
1152         if (*raw != '=')
1153                 return -1;
1154         raw++;
1155
1156         while (*raw && !isspace(*raw) && *raw != ';')
1157                 strbuf_addch(out, *raw++);
1158         return 0;
1159 }
1160
1161 /*
1162  * Extract a normalized version of the content type, with any
1163  * spaces suppressed, all letters lowercased, and no trailing ";"
1164  * or parameters.
1165  *
1166  * Note that we will silently remove even invalid whitespace. For
1167  * example, "text / plain" is specifically forbidden by RFC 2616,
1168  * but "text/plain" is the only reasonable output, and this keeps
1169  * our code simple.
1170  *
1171  * If the "charset" argument is not NULL, store the value of any
1172  * charset parameter there.
1173  *
1174  * Example:
1175  *   "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1176  *   "text / plain" -> "text/plain"
1177  */
1178 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1179                                  struct strbuf *charset)
1180 {
1181         const char *p;
1182
1183         strbuf_reset(type);
1184         strbuf_grow(type, raw->len);
1185         for (p = raw->buf; *p; p++) {
1186                 if (isspace(*p))
1187                         continue;
1188                 if (*p == ';') {
1189                         p++;
1190                         break;
1191                 }
1192                 strbuf_addch(type, tolower(*p));
1193         }
1194
1195         if (!charset)
1196                 return;
1197
1198         strbuf_reset(charset);
1199         while (*p) {
1200                 while (isspace(*p) || *p == ';')
1201                         p++;
1202                 if (!extract_param(p, "charset", charset))
1203                         return;
1204                 while (*p && !isspace(*p))
1205                         p++;
1206         }
1207
1208         if (!charset->len && starts_with(type->buf, "text/"))
1209                 strbuf_addstr(charset, "ISO-8859-1");
1210 }
1211
1212 static void write_accept_language(struct strbuf *buf)
1213 {
1214         /*
1215          * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1216          * that, q-value will be smaller than 0.001, the minimum q-value the
1217          * HTTP specification allows. See
1218          * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1219          */
1220         const int MAX_DECIMAL_PLACES = 3;
1221         const int MAX_LANGUAGE_TAGS = 1000;
1222         const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1223         char **language_tags = NULL;
1224         int num_langs = 0;
1225         const char *s = get_preferred_languages();
1226         int i;
1227         struct strbuf tag = STRBUF_INIT;
1228
1229         /* Don't add Accept-Language header if no language is preferred. */
1230         if (!s)
1231                 return;
1232
1233         /*
1234          * Split the colon-separated string of preferred languages into
1235          * language_tags array.
1236          */
1237         do {
1238                 /* collect language tag */
1239                 for (; *s && (isalnum(*s) || *s == '_'); s++)
1240                         strbuf_addch(&tag, *s == '_' ? '-' : *s);
1241
1242                 /* skip .codeset, @modifier and any other unnecessary parts */
1243                 while (*s && *s != ':')
1244                         s++;
1245
1246                 if (tag.len) {
1247                         num_langs++;
1248                         REALLOC_ARRAY(language_tags, num_langs);
1249                         language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1250                         if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1251                                 break;
1252                 }
1253         } while (*s++);
1254
1255         /* write Accept-Language header into buf */
1256         if (num_langs) {
1257                 int last_buf_len = 0;
1258                 int max_q;
1259                 int decimal_places;
1260                 char q_format[32];
1261
1262                 /* add '*' */
1263                 REALLOC_ARRAY(language_tags, num_langs + 1);
1264                 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1265
1266                 /* compute decimal_places */
1267                 for (max_q = 1, decimal_places = 0;
1268                      max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1269                      decimal_places++, max_q *= 10)
1270                         ;
1271
1272                 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1273
1274                 strbuf_addstr(buf, "Accept-Language: ");
1275
1276                 for (i = 0; i < num_langs; i++) {
1277                         if (i > 0)
1278                                 strbuf_addstr(buf, ", ");
1279
1280                         strbuf_addstr(buf, language_tags[i]);
1281
1282                         if (i > 0)
1283                                 strbuf_addf(buf, q_format, max_q - i);
1284
1285                         if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1286                                 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1287                                 break;
1288                         }
1289
1290                         last_buf_len = buf->len;
1291                 }
1292         }
1293
1294         /* free language tags -- last one is a static '*' */
1295         for (i = 0; i < num_langs - 1; i++)
1296                 free(language_tags[i]);
1297         free(language_tags);
1298 }
1299
1300 /*
1301  * Get an Accept-Language header which indicates user's preferred languages.
1302  *
1303  * Examples:
1304  *   LANGUAGE= -> ""
1305  *   LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1306  *   LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1307  *   LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1308  *   LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1309  *   LANGUAGE= LANG=C -> ""
1310  */
1311 static const char *get_accept_language(void)
1312 {
1313         if (!cached_accept_language) {
1314                 struct strbuf buf = STRBUF_INIT;
1315                 write_accept_language(&buf);
1316                 if (buf.len > 0)
1317                         cached_accept_language = strbuf_detach(&buf, NULL);
1318         }
1319
1320         return cached_accept_language;
1321 }
1322
1323 static void http_opt_request_remainder(CURL *curl, off_t pos)
1324 {
1325         char buf[128];
1326         xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1327         curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1328 }
1329
1330 /* http_request() targets */
1331 #define HTTP_REQUEST_STRBUF     0
1332 #define HTTP_REQUEST_FILE       1
1333
1334 static int http_request(const char *url,
1335                         void *result, int target,
1336                         const struct http_get_options *options)
1337 {
1338         struct active_request_slot *slot;
1339         struct slot_results results;
1340         struct curl_slist *headers = NULL;
1341         struct strbuf buf = STRBUF_INIT;
1342         const char *accept_language;
1343         int ret;
1344
1345         slot = get_active_slot();
1346         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1347
1348         if (result == NULL) {
1349                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1350         } else {
1351                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1352                 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1353
1354                 if (target == HTTP_REQUEST_FILE) {
1355                         off_t posn = ftello(result);
1356                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1357                                          fwrite);
1358                         if (posn > 0)
1359                                 http_opt_request_remainder(slot->curl, posn);
1360                 } else
1361                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1362                                          fwrite_buffer);
1363         }
1364
1365         accept_language = get_accept_language();
1366
1367         if (accept_language)
1368                 headers = curl_slist_append(headers, accept_language);
1369
1370         strbuf_addstr(&buf, "Pragma:");
1371         if (options && options->no_cache)
1372                 strbuf_addstr(&buf, " no-cache");
1373         if (options && options->keep_error)
1374                 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1375
1376         headers = curl_slist_append(headers, buf.buf);
1377
1378         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1379         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1380         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1381
1382         ret = run_one_slot(slot, &results);
1383
1384         if (options && options->content_type) {
1385                 struct strbuf raw = STRBUF_INIT;
1386                 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1387                 extract_content_type(&raw, options->content_type,
1388                                      options->charset);
1389                 strbuf_release(&raw);
1390         }
1391
1392         if (options && options->effective_url)
1393                 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1394                                 options->effective_url);
1395
1396         curl_slist_free_all(headers);
1397         strbuf_release(&buf);
1398
1399         return ret;
1400 }
1401
1402 /*
1403  * Update the "base" url to a more appropriate value, as deduced by
1404  * redirects seen when requesting a URL starting with "url".
1405  *
1406  * The "asked" parameter is a URL that we asked curl to access, and must begin
1407  * with "base".
1408  *
1409  * The "got" parameter is the URL that curl reported to us as where we ended
1410  * up.
1411  *
1412  * Returns 1 if we updated the base url, 0 otherwise.
1413  *
1414  * Our basic strategy is to compare "base" and "asked" to find the bits
1415  * specific to our request. We then strip those bits off of "got" to yield the
1416  * new base. So for example, if our base is "http://example.com/foo.git",
1417  * and we ask for "http://example.com/foo.git/info/refs", we might end up
1418  * with "https://other.example.com/foo.git/info/refs". We would want the
1419  * new URL to become "https://other.example.com/foo.git".
1420  *
1421  * Note that this assumes a sane redirect scheme. It's entirely possible
1422  * in the example above to end up at a URL that does not even end in
1423  * "info/refs".  In such a case we simply punt, as there is not much we can
1424  * do (and such a scheme is unlikely to represent a real git repository,
1425  * which means we are likely about to abort anyway).
1426  */
1427 static int update_url_from_redirect(struct strbuf *base,
1428                                     const char *asked,
1429                                     const struct strbuf *got)
1430 {
1431         const char *tail;
1432         size_t tail_len;
1433
1434         if (!strcmp(asked, got->buf))
1435                 return 0;
1436
1437         if (!skip_prefix(asked, base->buf, &tail))
1438                 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1439                     asked, base->buf);
1440
1441         tail_len = strlen(tail);
1442
1443         if (got->len < tail_len ||
1444             strcmp(tail, got->buf + got->len - tail_len))
1445                 return 0; /* insane redirect scheme */
1446
1447         strbuf_reset(base);
1448         strbuf_add(base, got->buf, got->len - tail_len);
1449         return 1;
1450 }
1451
1452 static int http_request_reauth(const char *url,
1453                                void *result, int target,
1454                                struct http_get_options *options)
1455 {
1456         int ret = http_request(url, result, target, options);
1457
1458         if (options && options->effective_url && options->base_url) {
1459                 if (update_url_from_redirect(options->base_url,
1460                                              url, options->effective_url)) {
1461                         credential_from_url(&http_auth, options->base_url->buf);
1462                         url = options->effective_url->buf;
1463                 }
1464         }
1465
1466         if (ret != HTTP_REAUTH)
1467                 return ret;
1468
1469         /*
1470          * If we are using KEEP_ERROR, the previous request may have
1471          * put cruft into our output stream; we should clear it out before
1472          * making our next request. We only know how to do this for
1473          * the strbuf case, but that is enough to satisfy current callers.
1474          */
1475         if (options && options->keep_error) {
1476                 switch (target) {
1477                 case HTTP_REQUEST_STRBUF:
1478                         strbuf_reset(result);
1479                         break;
1480                 default:
1481                         die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1482                 }
1483         }
1484
1485         credential_fill(&http_auth);
1486
1487         return http_request(url, result, target, options);
1488 }
1489
1490 int http_get_strbuf(const char *url,
1491                     struct strbuf *result,
1492                     struct http_get_options *options)
1493 {
1494         return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1495 }
1496
1497 /*
1498  * Downloads a URL and stores the result in the given file.
1499  *
1500  * If a previous interrupted download is detected (i.e. a previous temporary
1501  * file is still around) the download is resumed.
1502  */
1503 static int http_get_file(const char *url, const char *filename,
1504                          struct http_get_options *options)
1505 {
1506         int ret;
1507         struct strbuf tmpfile = STRBUF_INIT;
1508         FILE *result;
1509
1510         strbuf_addf(&tmpfile, "%s.temp", filename);
1511         result = fopen(tmpfile.buf, "a");
1512         if (!result) {
1513                 error("Unable to open local file %s", tmpfile.buf);
1514                 ret = HTTP_ERROR;
1515                 goto cleanup;
1516         }
1517
1518         ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1519         fclose(result);
1520
1521         if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1522                 ret = HTTP_ERROR;
1523 cleanup:
1524         strbuf_release(&tmpfile);
1525         return ret;
1526 }
1527
1528 int http_fetch_ref(const char *base, struct ref *ref)
1529 {
1530         struct http_get_options options = {0};
1531         char *url;
1532         struct strbuf buffer = STRBUF_INIT;
1533         int ret = -1;
1534
1535         options.no_cache = 1;
1536
1537         url = quote_ref_url(base, ref->name);
1538         if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1539                 strbuf_rtrim(&buffer);
1540                 if (buffer.len == 40)
1541                         ret = get_oid_hex(buffer.buf, &ref->old_oid);
1542                 else if (starts_with(buffer.buf, "ref: ")) {
1543                         ref->symref = xstrdup(buffer.buf + 5);
1544                         ret = 0;
1545                 }
1546         }
1547
1548         strbuf_release(&buffer);
1549         free(url);
1550         return ret;
1551 }
1552
1553 /* Helpers for fetching packs */
1554 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1555 {
1556         char *url, *tmp;
1557         struct strbuf buf = STRBUF_INIT;
1558
1559         if (http_is_verbose)
1560                 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1561
1562         end_url_with_slash(&buf, base_url);
1563         strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1564         url = strbuf_detach(&buf, NULL);
1565
1566         strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1567         tmp = strbuf_detach(&buf, NULL);
1568
1569         if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1570                 error("Unable to get pack index %s", url);
1571                 free(tmp);
1572                 tmp = NULL;
1573         }
1574
1575         free(url);
1576         return tmp;
1577 }
1578
1579 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1580         unsigned char *sha1, const char *base_url)
1581 {
1582         struct packed_git *new_pack;
1583         char *tmp_idx = NULL;
1584         int ret;
1585
1586         if (has_pack_index(sha1)) {
1587                 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1588                 if (!new_pack)
1589                         return -1; /* parse_pack_index() already issued error message */
1590                 goto add_pack;
1591         }
1592
1593         tmp_idx = fetch_pack_index(sha1, base_url);
1594         if (!tmp_idx)
1595                 return -1;
1596
1597         new_pack = parse_pack_index(sha1, tmp_idx);
1598         if (!new_pack) {
1599                 unlink(tmp_idx);
1600                 free(tmp_idx);
1601
1602                 return -1; /* parse_pack_index() already issued error message */
1603         }
1604
1605         ret = verify_pack_index(new_pack);
1606         if (!ret) {
1607                 close_pack_index(new_pack);
1608                 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1609         }
1610         free(tmp_idx);
1611         if (ret)
1612                 return -1;
1613
1614 add_pack:
1615         new_pack->next = *packs_head;
1616         *packs_head = new_pack;
1617         return 0;
1618 }
1619
1620 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1621 {
1622         struct http_get_options options = {0};
1623         int ret = 0, i = 0;
1624         char *url, *data;
1625         struct strbuf buf = STRBUF_INIT;
1626         unsigned char sha1[20];
1627
1628         end_url_with_slash(&buf, base_url);
1629         strbuf_addstr(&buf, "objects/info/packs");
1630         url = strbuf_detach(&buf, NULL);
1631
1632         options.no_cache = 1;
1633         ret = http_get_strbuf(url, &buf, &options);
1634         if (ret != HTTP_OK)
1635                 goto cleanup;
1636
1637         data = buf.buf;
1638         while (i < buf.len) {
1639                 switch (data[i]) {
1640                 case 'P':
1641                         i++;
1642                         if (i + 52 <= buf.len &&
1643                             starts_with(data + i, " pack-") &&
1644                             starts_with(data + i + 46, ".pack\n")) {
1645                                 get_sha1_hex(data + i + 6, sha1);
1646                                 fetch_and_setup_pack_index(packs_head, sha1,
1647                                                       base_url);
1648                                 i += 51;
1649                                 break;
1650                         }
1651                 default:
1652                         while (i < buf.len && data[i] != '\n')
1653                                 i++;
1654                 }
1655                 i++;
1656         }
1657
1658 cleanup:
1659         free(url);
1660         return ret;
1661 }
1662
1663 void release_http_pack_request(struct http_pack_request *preq)
1664 {
1665         if (preq->packfile != NULL) {
1666                 fclose(preq->packfile);
1667                 preq->packfile = NULL;
1668         }
1669         preq->slot = NULL;
1670         free(preq->url);
1671         free(preq);
1672 }
1673
1674 int finish_http_pack_request(struct http_pack_request *preq)
1675 {
1676         struct packed_git **lst;
1677         struct packed_git *p = preq->target;
1678         char *tmp_idx;
1679         size_t len;
1680         struct child_process ip = CHILD_PROCESS_INIT;
1681         const char *ip_argv[8];
1682
1683         close_pack_index(p);
1684
1685         fclose(preq->packfile);
1686         preq->packfile = NULL;
1687
1688         lst = preq->lst;
1689         while (*lst != p)
1690                 lst = &((*lst)->next);
1691         *lst = (*lst)->next;
1692
1693         if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1694                 die("BUG: pack tmpfile does not end in .pack.temp?");
1695         tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1696
1697         ip_argv[0] = "index-pack";
1698         ip_argv[1] = "-o";
1699         ip_argv[2] = tmp_idx;
1700         ip_argv[3] = preq->tmpfile;
1701         ip_argv[4] = NULL;
1702
1703         ip.argv = ip_argv;
1704         ip.git_cmd = 1;
1705         ip.no_stdin = 1;
1706         ip.no_stdout = 1;
1707
1708         if (run_command(&ip)) {
1709                 unlink(preq->tmpfile);
1710                 unlink(tmp_idx);
1711                 free(tmp_idx);
1712                 return -1;
1713         }
1714
1715         unlink(sha1_pack_index_name(p->sha1));
1716
1717         if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1718          || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1719                 free(tmp_idx);
1720                 return -1;
1721         }
1722
1723         install_packed_git(p);
1724         free(tmp_idx);
1725         return 0;
1726 }
1727
1728 struct http_pack_request *new_http_pack_request(
1729         struct packed_git *target, const char *base_url)
1730 {
1731         off_t prev_posn = 0;
1732         struct strbuf buf = STRBUF_INIT;
1733         struct http_pack_request *preq;
1734
1735         preq = xcalloc(1, sizeof(*preq));
1736         preq->target = target;
1737
1738         end_url_with_slash(&buf, base_url);
1739         strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1740                 sha1_to_hex(target->sha1));
1741         preq->url = strbuf_detach(&buf, NULL);
1742
1743         snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1744                 sha1_pack_name(target->sha1));
1745         preq->packfile = fopen(preq->tmpfile, "a");
1746         if (!preq->packfile) {
1747                 error("Unable to open local file %s for pack",
1748                       preq->tmpfile);
1749                 goto abort;
1750         }
1751
1752         preq->slot = get_active_slot();
1753         curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1754         curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1755         curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1756         curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1757                 no_pragma_header);
1758
1759         /*
1760          * If there is data present from a previous transfer attempt,
1761          * resume where it left off
1762          */
1763         prev_posn = ftello(preq->packfile);
1764         if (prev_posn>0) {
1765                 if (http_is_verbose)
1766                         fprintf(stderr,
1767                                 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1768                                 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1769                 http_opt_request_remainder(preq->slot->curl, prev_posn);
1770         }
1771
1772         return preq;
1773
1774 abort:
1775         free(preq->url);
1776         free(preq);
1777         return NULL;
1778 }
1779
1780 /* Helpers for fetching objects (loose) */
1781 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1782                                void *data)
1783 {
1784         unsigned char expn[4096];
1785         size_t size = eltsize * nmemb;
1786         int posn = 0;
1787         struct http_object_request *freq =
1788                 (struct http_object_request *)data;
1789         do {
1790                 ssize_t retval = xwrite(freq->localfile,
1791                                         (char *) ptr + posn, size - posn);
1792                 if (retval < 0)
1793                         return posn;
1794                 posn += retval;
1795         } while (posn < size);
1796
1797         freq->stream.avail_in = size;
1798         freq->stream.next_in = (void *)ptr;
1799         do {
1800                 freq->stream.next_out = expn;
1801                 freq->stream.avail_out = sizeof(expn);
1802                 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1803                 git_SHA1_Update(&freq->c, expn,
1804                                 sizeof(expn) - freq->stream.avail_out);
1805         } while (freq->stream.avail_in && freq->zret == Z_OK);
1806         return size;
1807 }
1808
1809 struct http_object_request *new_http_object_request(const char *base_url,
1810         unsigned char *sha1)
1811 {
1812         char *hex = sha1_to_hex(sha1);
1813         const char *filename;
1814         char prevfile[PATH_MAX];
1815         int prevlocal;
1816         char prev_buf[PREV_BUF_SIZE];
1817         ssize_t prev_read = 0;
1818         off_t prev_posn = 0;
1819         struct http_object_request *freq;
1820
1821         freq = xcalloc(1, sizeof(*freq));
1822         hashcpy(freq->sha1, sha1);
1823         freq->localfile = -1;
1824
1825         filename = sha1_file_name(sha1);
1826         snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1827                  "%s.temp", filename);
1828
1829         snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1830         unlink_or_warn(prevfile);
1831         rename(freq->tmpfile, prevfile);
1832         unlink_or_warn(freq->tmpfile);
1833
1834         if (freq->localfile != -1)
1835                 error("fd leakage in start: %d", freq->localfile);
1836         freq->localfile = open(freq->tmpfile,
1837                                O_WRONLY | O_CREAT | O_EXCL, 0666);
1838         /*
1839          * This could have failed due to the "lazy directory creation";
1840          * try to mkdir the last path component.
1841          */
1842         if (freq->localfile < 0 && errno == ENOENT) {
1843                 char *dir = strrchr(freq->tmpfile, '/');
1844                 if (dir) {
1845                         *dir = 0;
1846                         mkdir(freq->tmpfile, 0777);
1847                         *dir = '/';
1848                 }
1849                 freq->localfile = open(freq->tmpfile,
1850                                        O_WRONLY | O_CREAT | O_EXCL, 0666);
1851         }
1852
1853         if (freq->localfile < 0) {
1854                 error("Couldn't create temporary file %s: %s",
1855                       freq->tmpfile, strerror(errno));
1856                 goto abort;
1857         }
1858
1859         git_inflate_init(&freq->stream);
1860
1861         git_SHA1_Init(&freq->c);
1862
1863         freq->url = get_remote_object_url(base_url, hex, 0);
1864
1865         /*
1866          * If a previous temp file is present, process what was already
1867          * fetched.
1868          */
1869         prevlocal = open(prevfile, O_RDONLY);
1870         if (prevlocal != -1) {
1871                 do {
1872                         prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1873                         if (prev_read>0) {
1874                                 if (fwrite_sha1_file(prev_buf,
1875                                                      1,
1876                                                      prev_read,
1877                                                      freq) == prev_read) {
1878                                         prev_posn += prev_read;
1879                                 } else {
1880                                         prev_read = -1;
1881                                 }
1882                         }
1883                 } while (prev_read > 0);
1884                 close(prevlocal);
1885         }
1886         unlink_or_warn(prevfile);
1887
1888         /*
1889          * Reset inflate/SHA1 if there was an error reading the previous temp
1890          * file; also rewind to the beginning of the local file.
1891          */
1892         if (prev_read == -1) {
1893                 memset(&freq->stream, 0, sizeof(freq->stream));
1894                 git_inflate_init(&freq->stream);
1895                 git_SHA1_Init(&freq->c);
1896                 if (prev_posn>0) {
1897                         prev_posn = 0;
1898                         lseek(freq->localfile, 0, SEEK_SET);
1899                         if (ftruncate(freq->localfile, 0) < 0) {
1900                                 error("Couldn't truncate temporary file %s: %s",
1901                                           freq->tmpfile, strerror(errno));
1902                                 goto abort;
1903                         }
1904                 }
1905         }
1906
1907         freq->slot = get_active_slot();
1908
1909         curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1910         curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1911         curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1912         curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1913         curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1914
1915         /*
1916          * If we have successfully processed data from a previous fetch
1917          * attempt, only fetch the data we don't already have.
1918          */
1919         if (prev_posn>0) {
1920                 if (http_is_verbose)
1921                         fprintf(stderr,
1922                                 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
1923                                 hex, (uintmax_t)prev_posn);
1924                 http_opt_request_remainder(freq->slot->curl, prev_posn);
1925         }
1926
1927         return freq;
1928
1929 abort:
1930         free(freq->url);
1931         free(freq);
1932         return NULL;
1933 }
1934
1935 void process_http_object_request(struct http_object_request *freq)
1936 {
1937         if (freq->slot == NULL)
1938                 return;
1939         freq->curl_result = freq->slot->curl_result;
1940         freq->http_code = freq->slot->http_code;
1941         freq->slot = NULL;
1942 }
1943
1944 int finish_http_object_request(struct http_object_request *freq)
1945 {
1946         struct stat st;
1947
1948         close(freq->localfile);
1949         freq->localfile = -1;
1950
1951         process_http_object_request(freq);
1952
1953         if (freq->http_code == 416) {
1954                 warning("requested range invalid; we may already have all the data.");
1955         } else if (freq->curl_result != CURLE_OK) {
1956                 if (stat(freq->tmpfile, &st) == 0)
1957                         if (st.st_size == 0)
1958                                 unlink_or_warn(freq->tmpfile);
1959                 return -1;
1960         }
1961
1962         git_inflate_end(&freq->stream);
1963         git_SHA1_Final(freq->real_sha1, &freq->c);
1964         if (freq->zret != Z_STREAM_END) {
1965                 unlink_or_warn(freq->tmpfile);
1966                 return -1;
1967         }
1968         if (hashcmp(freq->sha1, freq->real_sha1)) {
1969                 unlink_or_warn(freq->tmpfile);
1970                 return -1;
1971         }
1972         freq->rename =
1973                 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
1974
1975         return freq->rename;
1976 }
1977
1978 void abort_http_object_request(struct http_object_request *freq)
1979 {
1980         unlink_or_warn(freq->tmpfile);
1981
1982         release_http_object_request(freq);
1983 }
1984
1985 void release_http_object_request(struct http_object_request *freq)
1986 {
1987         if (freq->localfile != -1) {
1988                 close(freq->localfile);
1989                 freq->localfile = -1;
1990         }
1991         if (freq->url != NULL) {
1992                 free(freq->url);
1993                 freq->url = NULL;
1994         }
1995         if (freq->slot != NULL) {
1996                 freq->slot->callback_func = NULL;
1997                 freq->slot->callback_data = NULL;
1998                 release_active_slot(freq->slot);
1999                 freq->slot = NULL;
2000         }
2001 }