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