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