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