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