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