OSDN Git Service

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