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