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