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