OSDN Git Service

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