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