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