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