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