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