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