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