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