]> git.ipfire.org Git - thirdparty/git.git/blame - http.c
Merge branch 'maint'
[thirdparty/git.git] / http.c
CommitLineData
29508e1e 1#include "http.h"
2264dfa5 2#include "pack.h"
de1a2fdd 3#include "sideband.h"
29508e1e
NH
4
5int data_received;
4251ccbd 6int active_requests;
e9176745 7int http_is_verbose;
de1a2fdd 8size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
29508e1e
NH
9
10#ifdef USE_CURL_MULTI
cc3530e8
MH
11static int max_requests = -1;
12static CURLM *curlm;
29508e1e
NH
13#endif
14#ifndef NO_CURL_EASY_DUPHANDLE
cc3530e8 15static CURL *curl_default;
29508e1e 16#endif
5424bc55
TRC
17
18#define PREV_BUF_SIZE 4096
19#define RANGE_HEADER_SIZE 30
20
29508e1e
NH
21char curl_errorstr[CURL_ERROR_SIZE];
22
cc3530e8 23static int curl_ssl_verify = -1;
4251ccbd 24static const char *ssl_cert;
ef52aafa 25#if LIBCURL_VERSION_NUM >= 0x070903
4251ccbd 26static const char *ssl_key;
29508e1e
NH
27#endif
28#if LIBCURL_VERSION_NUM >= 0x070908
4251ccbd 29static const char *ssl_capath;
29508e1e 30#endif
4251ccbd 31static const char *ssl_cainfo;
cc3530e8
MH
32static long curl_low_speed_limit = -1;
33static long curl_low_speed_time = -1;
4251ccbd
JH
34static int curl_ftp_no_epsv;
35static const char *curl_http_proxy;
c33976cb 36static char *user_name, *user_pass;
29508e1e 37
30dd9163
ML
38#if LIBCURL_VERSION_NUM >= 0x071700
39/* Use CURLOPT_KEYPASSWD as is */
40#elif LIBCURL_VERSION_NUM >= 0x070903
41#define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
42#else
43#define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
44#endif
45
46static char *ssl_cert_password;
47static int ssl_cert_password_required;
48
cc3530e8 49static struct curl_slist *pragma_header;
5424bc55 50static struct curl_slist *no_pragma_header;
e9176745 51
4251ccbd 52static struct active_request_slot *active_queue_head;
29508e1e 53
f444e528 54size_t fread_buffer(void *ptr, size_t eltsize, size_t nmemb, void *buffer_)
29508e1e
NH
55{
56 size_t size = eltsize * nmemb;
f444e528
JH
57 struct buffer *buffer = buffer_;
58
028c2976
MH
59 if (size > buffer->buf.len - buffer->posn)
60 size = buffer->buf.len - buffer->posn;
61 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
29508e1e 62 buffer->posn += size;
028c2976 63
29508e1e
NH
64 return size;
65}
66
3944ba0c
MS
67#ifndef NO_CURL_IOCTL
68curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
69{
70 struct buffer *buffer = clientp;
71
72 switch (cmd) {
73 case CURLIOCMD_NOP:
74 return CURLIOE_OK;
75
76 case CURLIOCMD_RESTARTREAD:
77 buffer->posn = 0;
78 return CURLIOE_OK;
79
80 default:
81 return CURLIOE_UNKNOWNCMD;
82 }
83}
84#endif
85
f444e528 86size_t fwrite_buffer(const void *ptr, size_t eltsize, size_t nmemb, void *buffer_)
29508e1e
NH
87{
88 size_t size = eltsize * nmemb;
f444e528
JH
89 struct strbuf *buffer = buffer_;
90
028c2976 91 strbuf_add(buffer, ptr, size);
29508e1e
NH
92 data_received++;
93 return size;
94}
95
f444e528 96size_t fwrite_null(const void *ptr, size_t eltsize, size_t nmemb, void *strbuf)
29508e1e
NH
97{
98 data_received++;
99 return eltsize * nmemb;
100}
101
29508e1e
NH
102#ifdef USE_CURL_MULTI
103static void process_curl_messages(void)
104{
105 int num_messages;
106 struct active_request_slot *slot;
107 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
108
109 while (curl_message != NULL) {
110 if (curl_message->msg == CURLMSG_DONE) {
111 int curl_result = curl_message->data.result;
112 slot = active_queue_head;
113 while (slot != NULL &&
114 slot->curl != curl_message->easy_handle)
115 slot = slot->next;
116 if (slot != NULL) {
117 curl_multi_remove_handle(curlm, slot->curl);
118 slot->curl_result = curl_result;
119 finish_active_slot(slot);
120 } else {
121 fprintf(stderr, "Received DONE message for unknown request!\n");
122 }
123 } else {
124 fprintf(stderr, "Unknown CURL message received: %d\n",
125 (int)curl_message->msg);
126 }
127 curl_message = curl_multi_info_read(curlm, &num_messages);
128 }
129}
130#endif
131
ef90d6d4 132static int http_options(const char *var, const char *value, void *cb)
29508e1e
NH
133{
134 if (!strcmp("http.sslverify", var)) {
7059cd99 135 curl_ssl_verify = git_config_bool(var, value);
29508e1e
NH
136 return 0;
137 }
7059cd99
JH
138 if (!strcmp("http.sslcert", var))
139 return git_config_string(&ssl_cert, var, value);
ef52aafa 140#if LIBCURL_VERSION_NUM >= 0x070903
7059cd99
JH
141 if (!strcmp("http.sslkey", var))
142 return git_config_string(&ssl_key, var, value);
29508e1e
NH
143#endif
144#if LIBCURL_VERSION_NUM >= 0x070908
7059cd99
JH
145 if (!strcmp("http.sslcapath", var))
146 return git_config_string(&ssl_capath, var, value);
29508e1e 147#endif
7059cd99
JH
148 if (!strcmp("http.sslcainfo", var))
149 return git_config_string(&ssl_cainfo, var, value);
754ae192
ML
150 if (!strcmp("http.sslcertpasswordprotected", var)) {
151 if (git_config_bool(var, value))
152 ssl_cert_password_required = 1;
153 return 0;
154 }
a6080a0a 155#ifdef USE_CURL_MULTI
29508e1e 156 if (!strcmp("http.maxrequests", var)) {
7059cd99 157 max_requests = git_config_int(var, value);
29508e1e
NH
158 return 0;
159 }
160#endif
29508e1e 161 if (!strcmp("http.lowspeedlimit", var)) {
7059cd99 162 curl_low_speed_limit = (long)git_config_int(var, value);
29508e1e
NH
163 return 0;
164 }
165 if (!strcmp("http.lowspeedtime", var)) {
7059cd99 166 curl_low_speed_time = (long)git_config_int(var, value);
29508e1e
NH
167 return 0;
168 }
169
3ea099d4
SK
170 if (!strcmp("http.noepsv", var)) {
171 curl_ftp_no_epsv = git_config_bool(var, value);
172 return 0;
173 }
7059cd99
JH
174 if (!strcmp("http.proxy", var))
175 return git_config_string(&curl_http_proxy, var, value);
3ea099d4 176
de1a2fdd
SP
177 if (!strcmp("http.postbuffer", var)) {
178 http_post_buffer = git_config_int(var, value);
179 if (http_post_buffer < LARGE_PACKET_MAX)
180 http_post_buffer = LARGE_PACKET_MAX;
181 return 0;
182 }
183
29508e1e 184 /* Fall back on the default ones */
ef90d6d4 185 return git_default_config(var, value, cb);
29508e1e
NH
186}
187
c33976cb
JH
188static void init_curl_http_auth(CURL *result)
189{
750d9305 190 if (user_name) {
c33976cb
JH
191 struct strbuf up = STRBUF_INIT;
192 if (!user_pass)
193 user_pass = xstrdup(getpass("Password: "));
194 strbuf_addf(&up, "%s:%s", user_name, user_pass);
195 curl_easy_setopt(result, CURLOPT_USERPWD,
196 strbuf_detach(&up, NULL));
197 }
198}
199
30dd9163
ML
200static int has_cert_password(void)
201{
202 if (ssl_cert_password != NULL)
203 return 1;
204 if (ssl_cert == NULL || ssl_cert_password_required != 1)
205 return 0;
206 /* Only prompt the user once. */
207 ssl_cert_password_required = -1;
208 ssl_cert_password = getpass("Certificate Password: ");
209 if (ssl_cert_password != NULL) {
210 ssl_cert_password = xstrdup(ssl_cert_password);
211 return 1;
212 } else
213 return 0;
214}
215
4251ccbd 216static CURL *get_curl_handle(void)
11979b98 217{
4251ccbd 218 CURL *result = curl_easy_init();
11979b98 219
a5ccc597
JH
220 if (!curl_ssl_verify) {
221 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
222 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
223 } else {
224 /* Verify authenticity of the peer's certificate */
225 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
226 /* The name in the cert must match whom we tried to connect */
227 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
228 }
229
11979b98
JH
230#if LIBCURL_VERSION_NUM >= 0x070907
231 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
232#endif
233
c33976cb
JH
234 init_curl_http_auth(result);
235
11979b98
JH
236 if (ssl_cert != NULL)
237 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
30dd9163
ML
238 if (has_cert_password())
239 curl_easy_setopt(result, CURLOPT_KEYPASSWD, ssl_cert_password);
ef52aafa 240#if LIBCURL_VERSION_NUM >= 0x070903
11979b98
JH
241 if (ssl_key != NULL)
242 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
243#endif
244#if LIBCURL_VERSION_NUM >= 0x070908
245 if (ssl_capath != NULL)
246 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
247#endif
248 if (ssl_cainfo != NULL)
249 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
250 curl_easy_setopt(result, CURLOPT_FAILONERROR, 1);
251
252 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
253 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
254 curl_low_speed_limit);
255 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
256 curl_low_speed_time);
257 }
258
259 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
260
7982d74e
MW
261 if (getenv("GIT_CURL_VERBOSE"))
262 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
263
20fc9bc5
NH
264 curl_easy_setopt(result, CURLOPT_USERAGENT, GIT_USER_AGENT);
265
3ea099d4
SK
266 if (curl_ftp_no_epsv)
267 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
268
9c5665aa
SV
269 if (curl_http_proxy)
270 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
271
11979b98
JH
272 return result;
273}
274
c33976cb
JH
275static void http_auth_init(const char *url)
276{
277 char *at, *colon, *cp, *slash;
278 int len;
279
280 cp = strstr(url, "://");
281 if (!cp)
282 return;
283
284 /*
285 * Ok, the URL looks like "proto://something". Which one?
286 * "proto://<user>:<pass>@<host>/...",
287 * "proto://<user>@<host>/...", or just
288 * "proto://<host>/..."?
289 */
290 cp += 3;
291 at = strchr(cp, '@');
292 colon = strchr(cp, ':');
293 slash = strchrnul(cp, '/');
294 if (!at || slash <= at)
295 return; /* No credentials */
296 if (!colon || at <= colon) {
297 /* Only username */
298 len = at - cp;
299 user_name = xmalloc(len + 1);
300 memcpy(user_name, cp, len);
301 user_name[len] = '\0';
302 user_pass = NULL;
303 } else {
304 len = colon - cp;
305 user_name = xmalloc(len + 1);
306 memcpy(user_name, cp, len);
307 user_name[len] = '\0';
308 len = at - (colon + 1);
309 user_pass = xmalloc(len + 1);
310 memcpy(user_pass, colon + 1, len);
311 user_pass[len] = '\0';
312 }
313}
314
7059cd99
JH
315static void set_from_env(const char **var, const char *envname)
316{
317 const char *val = getenv(envname);
318 if (val)
319 *var = val;
320}
321
9fc6440d 322void http_init(struct remote *remote)
29508e1e
NH
323{
324 char *low_speed_limit;
325 char *low_speed_time;
326
e9176745
TRC
327 http_is_verbose = 0;
328
7059cd99
JH
329 git_config(http_options, NULL);
330
29508e1e
NH
331 curl_global_init(CURL_GLOBAL_ALL);
332
9fc6440d
MH
333 if (remote && remote->http_proxy)
334 curl_http_proxy = xstrdup(remote->http_proxy);
335
29508e1e 336 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
e9176745 337 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
29508e1e
NH
338
339#ifdef USE_CURL_MULTI
340 {
341 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
342 if (http_max_requests != NULL)
343 max_requests = atoi(http_max_requests);
344 }
345
346 curlm = curl_multi_init();
347 if (curlm == NULL) {
348 fprintf(stderr, "Error creating curl multi handle.\n");
349 exit(1);
350 }
351#endif
352
353 if (getenv("GIT_SSL_NO_VERIFY"))
354 curl_ssl_verify = 0;
355
7059cd99 356 set_from_env(&ssl_cert, "GIT_SSL_CERT");
ef52aafa 357#if LIBCURL_VERSION_NUM >= 0x070903
7059cd99 358 set_from_env(&ssl_key, "GIT_SSL_KEY");
29508e1e
NH
359#endif
360#if LIBCURL_VERSION_NUM >= 0x070908
7059cd99 361 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
29508e1e 362#endif
7059cd99 363 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
29508e1e
NH
364
365 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
366 if (low_speed_limit != NULL)
367 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
368 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
369 if (low_speed_time != NULL)
370 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
371
29508e1e
NH
372 if (curl_ssl_verify == -1)
373 curl_ssl_verify = 1;
374
375#ifdef USE_CURL_MULTI
376 if (max_requests < 1)
377 max_requests = DEFAULT_MAX_REQUESTS;
378#endif
379
3ea099d4
SK
380 if (getenv("GIT_CURL_FTP_NO_EPSV"))
381 curl_ftp_no_epsv = 1;
382
30dd9163 383 if (remote && remote->url && remote->url[0]) {
c33976cb 384 http_auth_init(remote->url[0]);
754ae192
ML
385 if (!ssl_cert_password_required &&
386 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
387 !prefixcmp(remote->url[0], "https://"))
30dd9163
ML
388 ssl_cert_password_required = 1;
389 }
c33976cb 390
29508e1e
NH
391#ifndef NO_CURL_EASY_DUPHANDLE
392 curl_default = get_curl_handle();
393#endif
394}
395
396void http_cleanup(void)
397{
398 struct active_request_slot *slot = active_queue_head;
29508e1e
NH
399
400 while (slot != NULL) {
3278cd0a 401 struct active_request_slot *next = slot->next;
f23d1f76 402 if (slot->curl != NULL) {
29508e1e 403#ifdef USE_CURL_MULTI
f23d1f76 404 curl_multi_remove_handle(curlm, slot->curl);
29508e1e 405#endif
29508e1e 406 curl_easy_cleanup(slot->curl);
f23d1f76 407 }
3278cd0a
SP
408 free(slot);
409 slot = next;
29508e1e 410 }
3278cd0a 411 active_queue_head = NULL;
29508e1e
NH
412
413#ifndef NO_CURL_EASY_DUPHANDLE
414 curl_easy_cleanup(curl_default);
415#endif
416
417#ifdef USE_CURL_MULTI
418 curl_multi_cleanup(curlm);
419#endif
420 curl_global_cleanup();
b3ca4e4e
NH
421
422 curl_slist_free_all(pragma_header);
3278cd0a 423 pragma_header = NULL;
9fc6440d 424
e9176745
TRC
425 curl_slist_free_all(no_pragma_header);
426 no_pragma_header = NULL;
427
9fc6440d 428 if (curl_http_proxy) {
e4a80ecf 429 free((void *)curl_http_proxy);
9fc6440d
MH
430 curl_http_proxy = NULL;
431 }
30dd9163
ML
432
433 if (ssl_cert_password != NULL) {
434 memset(ssl_cert_password, 0, strlen(ssl_cert_password));
435 free(ssl_cert_password);
436 ssl_cert_password = NULL;
437 }
438 ssl_cert_password_required = 0;
29508e1e
NH
439}
440
29508e1e
NH
441struct active_request_slot *get_active_slot(void)
442{
443 struct active_request_slot *slot = active_queue_head;
444 struct active_request_slot *newslot;
445
446#ifdef USE_CURL_MULTI
447 int num_transfers;
448
449 /* Wait for a slot to open up if the queue is full */
450 while (active_requests >= max_requests) {
451 curl_multi_perform(curlm, &num_transfers);
4251ccbd 452 if (num_transfers < active_requests)
29508e1e 453 process_curl_messages();
29508e1e
NH
454 }
455#endif
456
4251ccbd 457 while (slot != NULL && slot->in_use)
29508e1e 458 slot = slot->next;
4251ccbd 459
29508e1e
NH
460 if (slot == NULL) {
461 newslot = xmalloc(sizeof(*newslot));
462 newslot->curl = NULL;
463 newslot->in_use = 0;
464 newslot->next = NULL;
465
466 slot = active_queue_head;
467 if (slot == NULL) {
468 active_queue_head = newslot;
469 } else {
4251ccbd 470 while (slot->next != NULL)
29508e1e 471 slot = slot->next;
29508e1e
NH
472 slot->next = newslot;
473 }
474 slot = newslot;
475 }
476
477 if (slot->curl == NULL) {
478#ifdef NO_CURL_EASY_DUPHANDLE
479 slot->curl = get_curl_handle();
480#else
481 slot->curl = curl_easy_duphandle(curl_default);
482#endif
483 }
484
485 active_requests++;
486 slot->in_use = 1;
487 slot->local = NULL;
c8568e13 488 slot->results = NULL;
baa7b67d 489 slot->finished = NULL;
29508e1e
NH
490 slot->callback_data = NULL;
491 slot->callback_func = NULL;
492 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
29508e1e 493 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
9094950d
NH
494 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
495 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
496 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
497 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
498 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
29508e1e
NH
499
500 return slot;
501}
502
503int start_active_slot(struct active_request_slot *slot)
504{
505#ifdef USE_CURL_MULTI
506 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
45c17412 507 int num_transfers;
29508e1e
NH
508
509 if (curlm_result != CURLM_OK &&
510 curlm_result != CURLM_CALL_MULTI_PERFORM) {
511 active_requests--;
512 slot->in_use = 0;
513 return 0;
514 }
45c17412
DB
515
516 /*
517 * We know there must be something to do, since we just added
518 * something.
519 */
520 curl_multi_perform(curlm, &num_transfers);
29508e1e
NH
521#endif
522 return 1;
523}
524
525#ifdef USE_CURL_MULTI
fc57b6aa
DB
526struct fill_chain {
527 void *data;
528 int (*fill)(void *);
529 struct fill_chain *next;
530};
531
4251ccbd 532static struct fill_chain *fill_cfg;
fc57b6aa
DB
533
534void add_fill_function(void *data, int (*fill)(void *))
535{
e8eec71d 536 struct fill_chain *new = xmalloc(sizeof(*new));
fc57b6aa
DB
537 struct fill_chain **linkp = &fill_cfg;
538 new->data = data;
539 new->fill = fill;
540 new->next = NULL;
541 while (*linkp)
542 linkp = &(*linkp)->next;
543 *linkp = new;
544}
545
45c17412
DB
546void fill_active_slots(void)
547{
548 struct active_request_slot *slot = active_queue_head;
549
fc57b6aa
DB
550 while (active_requests < max_requests) {
551 struct fill_chain *fill;
552 for (fill = fill_cfg; fill; fill = fill->next)
553 if (fill->fill(fill->data))
554 break;
555
556 if (!fill)
45c17412 557 break;
fc57b6aa 558 }
45c17412
DB
559
560 while (slot != NULL) {
561 if (!slot->in_use && slot->curl != NULL) {
562 curl_easy_cleanup(slot->curl);
563 slot->curl = NULL;
564 }
565 slot = slot->next;
566 }
567}
568
29508e1e
NH
569void step_active_slots(void)
570{
571 int num_transfers;
572 CURLMcode curlm_result;
573
574 do {
575 curlm_result = curl_multi_perform(curlm, &num_transfers);
576 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
577 if (num_transfers < active_requests) {
578 process_curl_messages();
579 fill_active_slots();
580 }
581}
582#endif
583
584void run_active_slot(struct active_request_slot *slot)
585{
586#ifdef USE_CURL_MULTI
587 long last_pos = 0;
588 long current_pos;
589 fd_set readfds;
590 fd_set writefds;
591 fd_set excfds;
592 int max_fd;
593 struct timeval select_timeout;
baa7b67d 594 int finished = 0;
29508e1e 595
baa7b67d
NH
596 slot->finished = &finished;
597 while (!finished) {
29508e1e
NH
598 data_received = 0;
599 step_active_slots();
600
601 if (!data_received && slot->local != NULL) {
602 current_pos = ftell(slot->local);
603 if (current_pos > last_pos)
604 data_received++;
605 last_pos = current_pos;
606 }
607
608 if (slot->in_use && !data_received) {
609 max_fd = 0;
610 FD_ZERO(&readfds);
611 FD_ZERO(&writefds);
612 FD_ZERO(&excfds);
613 select_timeout.tv_sec = 0;
614 select_timeout.tv_usec = 50000;
615 select(max_fd, &readfds, &writefds,
616 &excfds, &select_timeout);
617 }
618 }
619#else
620 while (slot->in_use) {
621 slot->curl_result = curl_easy_perform(slot->curl);
622 finish_active_slot(slot);
623 }
624#endif
625}
626
53f31389 627static void closedown_active_slot(struct active_request_slot *slot)
29508e1e 628{
028c2976
MH
629 active_requests--;
630 slot->in_use = 0;
53f31389
MW
631}
632
633void release_active_slot(struct active_request_slot *slot)
634{
635 closedown_active_slot(slot);
636 if (slot->curl) {
b3ca4e4e 637#ifdef USE_CURL_MULTI
53f31389 638 curl_multi_remove_handle(curlm, slot->curl);
b3ca4e4e 639#endif
53f31389
MW
640 curl_easy_cleanup(slot->curl);
641 slot->curl = NULL;
642 }
b3ca4e4e 643#ifdef USE_CURL_MULTI
53f31389 644 fill_active_slots();
b3ca4e4e 645#endif
53f31389
MW
646}
647
de1a2fdd 648void finish_active_slot(struct active_request_slot *slot)
53f31389
MW
649{
650 closedown_active_slot(slot);
028c2976 651 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
c8568e13 652
baa7b67d
NH
653 if (slot->finished != NULL)
654 (*slot->finished) = 1;
655
c8568e13
NH
656 /* Store slot results so they can be read after the slot is reused */
657 if (slot->results != NULL) {
658 slot->results->curl_result = slot->curl_result;
659 slot->results->http_code = slot->http_code;
660 }
661
028c2976 662 /* Run callback if appropriate */
4251ccbd 663 if (slot->callback_func != NULL)
028c2976 664 slot->callback_func(slot->callback_data);
29508e1e
NH
665}
666
667void finish_all_active_slots(void)
668{
669 struct active_request_slot *slot = active_queue_head;
670
671 while (slot != NULL)
672 if (slot->in_use) {
673 run_active_slot(slot);
674 slot = active_queue_head;
675 } else {
676 slot = slot->next;
677 }
678}
d7e92806 679
5ace994f 680/* Helpers for modifying and creating URLs */
d7e92806
MH
681static inline int needs_quote(int ch)
682{
683 if (((ch >= 'A') && (ch <= 'Z'))
684 || ((ch >= 'a') && (ch <= 'z'))
685 || ((ch >= '0') && (ch <= '9'))
686 || (ch == '/')
687 || (ch == '-')
688 || (ch == '.'))
689 return 0;
690 return 1;
691}
692
693static inline int hex(int v)
694{
4251ccbd
JH
695 if (v < 10)
696 return '0' + v;
697 else
698 return 'A' + v - 10;
d7e92806
MH
699}
700
5ace994f
TRC
701static void end_url_with_slash(struct strbuf *buf, const char *url)
702{
703 strbuf_addstr(buf, url);
704 if (buf->len && buf->buf[buf->len - 1] != '/')
705 strbuf_addstr(buf, "/");
706}
707
d7e92806
MH
708static char *quote_ref_url(const char *base, const char *ref)
709{
113106e0 710 struct strbuf buf = STRBUF_INIT;
d7e92806 711 const char *cp;
113106e0 712 int ch;
d7e92806 713
5ace994f 714 end_url_with_slash(&buf, base);
113106e0
TRC
715
716 for (cp = ref; (ch = *cp) != 0; cp++)
d7e92806 717 if (needs_quote(ch))
113106e0 718 strbuf_addf(&buf, "%%%02x", ch);
d7e92806 719 else
113106e0 720 strbuf_addch(&buf, *cp);
d7e92806 721
113106e0 722 return strbuf_detach(&buf, NULL);
d7e92806
MH
723}
724
5424bc55
TRC
725void append_remote_object_url(struct strbuf *buf, const char *url,
726 const char *hex,
727 int only_two_digit_prefix)
728{
800324c3
TRC
729 end_url_with_slash(buf, url);
730
731 strbuf_addf(buf, "objects/%.*s/", 2, hex);
5424bc55
TRC
732 if (!only_two_digit_prefix)
733 strbuf_addf(buf, "%s", hex+2);
734}
735
736char *get_remote_object_url(const char *url, const char *hex,
737 int only_two_digit_prefix)
738{
739 struct strbuf buf = STRBUF_INIT;
740 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
741 return strbuf_detach(&buf, NULL);
742}
743
e929cd20
MH
744/* http_request() targets */
745#define HTTP_REQUEST_STRBUF 0
746#define HTTP_REQUEST_FILE 1
747
748static int http_request(const char *url, void *result, int target, int options)
749{
750 struct active_request_slot *slot;
751 struct slot_results results;
752 struct curl_slist *headers = NULL;
753 struct strbuf buf = STRBUF_INIT;
754 int ret;
755
756 slot = get_active_slot();
757 slot->results = &results;
758 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
759
760 if (result == NULL) {
761 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
762 } else {
763 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
764 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
765
766 if (target == HTTP_REQUEST_FILE) {
767 long posn = ftell(result);
768 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
769 fwrite);
770 if (posn > 0) {
771 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
772 headers = curl_slist_append(headers, buf.buf);
773 strbuf_reset(&buf);
774 }
775 slot->local = result;
776 } else
777 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
778 fwrite_buffer);
779 }
780
781 strbuf_addstr(&buf, "Pragma:");
782 if (options & HTTP_NO_CACHE)
783 strbuf_addstr(&buf, " no-cache");
784
785 headers = curl_slist_append(headers, buf.buf);
786
787 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
788 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
789
790 if (start_active_slot(slot)) {
791 run_active_slot(slot);
792 if (results.curl_result == CURLE_OK)
793 ret = HTTP_OK;
794 else if (missing_target(&results))
795 ret = HTTP_MISSING_TARGET;
796 else
797 ret = HTTP_ERROR;
798 } else {
799 error("Unable to start HTTP request for %s", url);
800 ret = HTTP_START_FAILED;
801 }
802
803 slot->local = NULL;
804 curl_slist_free_all(headers);
805 strbuf_release(&buf);
806
807 return ret;
808}
809
810int http_get_strbuf(const char *url, struct strbuf *result, int options)
811{
812 return http_request(url, result, HTTP_REQUEST_STRBUF, options);
813}
814
815int http_get_file(const char *url, const char *filename, int options)
816{
817 int ret;
818 struct strbuf tmpfile = STRBUF_INIT;
819 FILE *result;
820
821 strbuf_addf(&tmpfile, "%s.temp", filename);
822 result = fopen(tmpfile.buf, "a");
823 if (! result) {
824 error("Unable to open local file %s", tmpfile.buf);
825 ret = HTTP_ERROR;
826 goto cleanup;
827 }
828
829 ret = http_request(url, result, HTTP_REQUEST_FILE, options);
830 fclose(result);
831
832 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
833 ret = HTTP_ERROR;
834cleanup:
835 strbuf_release(&tmpfile);
836 return ret;
837}
838
839int http_error(const char *url, int ret)
840{
841 /* http_request has already handled HTTP_START_FAILED. */
842 if (ret != HTTP_START_FAILED)
843 error("%s while accessing %s\n", curl_errorstr, url);
844
845 return ret;
846}
847
c13b2633 848int http_fetch_ref(const char *base, struct ref *ref)
d7e92806
MH
849{
850 char *url;
851 struct strbuf buffer = STRBUF_INIT;
0d5896e1 852 int ret = -1;
d7e92806 853
c13b2633 854 url = quote_ref_url(base, ref->name);
0d5896e1
MH
855 if (http_get_strbuf(url, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
856 strbuf_rtrim(&buffer);
857 if (buffer.len == 40)
858 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
859 else if (!prefixcmp(buffer.buf, "ref: ")) {
860 ref->symref = xstrdup(buffer.buf + 5);
861 ret = 0;
d7e92806 862 }
d7e92806
MH
863 }
864
865 strbuf_release(&buffer);
866 free(url);
867 return ret;
868}
b8caac2b
TRC
869
870/* Helpers for fetching packs */
871static int fetch_pack_index(unsigned char *sha1, const char *base_url)
872{
873 int ret = 0;
874 char *hex = xstrdup(sha1_to_hex(sha1));
875 char *filename;
b2025146 876 char *url = NULL;
b8caac2b 877 struct strbuf buf = STRBUF_INIT;
b8caac2b 878
b8caac2b
TRC
879 if (has_pack_index(sha1)) {
880 ret = 0;
39dc52cf 881 goto cleanup;
b8caac2b
TRC
882 }
883
884 if (http_is_verbose)
885 fprintf(stderr, "Getting index for pack %s\n", hex);
886
887 end_url_with_slash(&buf, base_url);
888 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hex);
889 url = strbuf_detach(&buf, NULL);
890
891 filename = sha1_pack_index_name(sha1);
39dc52cf
TRC
892 if (http_get_file(url, filename, 0) != HTTP_OK)
893 ret = error("Unable to get pack index %s\n", url);
b8caac2b 894
39dc52cf 895cleanup:
b8caac2b
TRC
896 free(hex);
897 free(url);
898 return ret;
899}
900
901static int fetch_and_setup_pack_index(struct packed_git **packs_head,
902 unsigned char *sha1, const char *base_url)
903{
904 struct packed_git *new_pack;
905
906 if (fetch_pack_index(sha1, base_url))
907 return -1;
908
909 new_pack = parse_pack_index(sha1);
910 if (!new_pack)
911 return -1; /* parse_pack_index() already issued error message */
912 new_pack->next = *packs_head;
913 *packs_head = new_pack;
914 return 0;
915}
916
917int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
918{
919 int ret = 0, i = 0;
920 char *url, *data;
921 struct strbuf buf = STRBUF_INIT;
922 unsigned char sha1[20];
923
924 end_url_with_slash(&buf, base_url);
925 strbuf_addstr(&buf, "objects/info/packs");
926 url = strbuf_detach(&buf, NULL);
927
928 ret = http_get_strbuf(url, &buf, HTTP_NO_CACHE);
929 if (ret != HTTP_OK)
930 goto cleanup;
931
932 data = buf.buf;
933 while (i < buf.len) {
934 switch (data[i]) {
935 case 'P':
936 i++;
937 if (i + 52 <= buf.len &&
938 !prefixcmp(data + i, " pack-") &&
939 !prefixcmp(data + i + 46, ".pack\n")) {
940 get_sha1_hex(data + i + 6, sha1);
941 fetch_and_setup_pack_index(packs_head, sha1,
942 base_url);
943 i += 51;
944 break;
945 }
946 default:
947 while (i < buf.len && data[i] != '\n')
948 i++;
949 }
950 i++;
951 }
952
953cleanup:
954 free(url);
955 return ret;
956}
2264dfa5
TRC
957
958void release_http_pack_request(struct http_pack_request *preq)
959{
960 if (preq->packfile != NULL) {
961 fclose(preq->packfile);
962 preq->packfile = NULL;
963 preq->slot->local = NULL;
964 }
965 if (preq->range_header != NULL) {
966 curl_slist_free_all(preq->range_header);
967 preq->range_header = NULL;
968 }
969 preq->slot = NULL;
970 free(preq->url);
971}
972
973int finish_http_pack_request(struct http_pack_request *preq)
974{
975 int ret;
976 struct packed_git **lst;
977
978 preq->target->pack_size = ftell(preq->packfile);
979
980 if (preq->packfile != NULL) {
981 fclose(preq->packfile);
982 preq->packfile = NULL;
983 preq->slot->local = NULL;
984 }
985
986 ret = move_temp_to_file(preq->tmpfile, preq->filename);
987 if (ret)
988 return ret;
989
990 lst = preq->lst;
991 while (*lst != preq->target)
992 lst = &((*lst)->next);
993 *lst = (*lst)->next;
994
995 if (verify_pack(preq->target))
996 return -1;
997 install_packed_git(preq->target);
998
999 return 0;
1000}
1001
1002struct http_pack_request *new_http_pack_request(
1003 struct packed_git *target, const char *base_url)
1004{
2264dfa5
TRC
1005 char *filename;
1006 long prev_posn = 0;
1007 char range[RANGE_HEADER_SIZE];
1008 struct strbuf buf = STRBUF_INIT;
1009 struct http_pack_request *preq;
1010
1011 preq = xmalloc(sizeof(*preq));
1012 preq->target = target;
1013 preq->range_header = NULL;
1014
1015 end_url_with_slash(&buf, base_url);
1016 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1017 sha1_to_hex(target->sha1));
bb99190e 1018 preq->url = strbuf_detach(&buf, NULL);
2264dfa5
TRC
1019
1020 filename = sha1_pack_name(target->sha1);
1021 snprintf(preq->filename, sizeof(preq->filename), "%s", filename);
1022 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp", filename);
1023 preq->packfile = fopen(preq->tmpfile, "a");
1024 if (!preq->packfile) {
1025 error("Unable to open local file %s for pack",
1026 preq->tmpfile);
1027 goto abort;
1028 }
1029
1030 preq->slot = get_active_slot();
1031 preq->slot->local = preq->packfile;
1032 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1033 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
bb99190e 1034 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2264dfa5
TRC
1035 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1036 no_pragma_header);
1037
1038 /*
1039 * If there is data present from a previous transfer attempt,
1040 * resume where it left off
1041 */
1042 prev_posn = ftell(preq->packfile);
1043 if (prev_posn>0) {
1044 if (http_is_verbose)
1045 fprintf(stderr,
1046 "Resuming fetch of pack %s at byte %ld\n",
1047 sha1_to_hex(target->sha1), prev_posn);
1048 sprintf(range, "Range: bytes=%ld-", prev_posn);
1049 preq->range_header = curl_slist_append(NULL, range);
1050 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1051 preq->range_header);
1052 }
1053
1054 return preq;
1055
1056abort:
1057 free(filename);
bb99190e 1058 free(preq->url);
5ae9ebfd 1059 free(preq);
2264dfa5
TRC
1060 return NULL;
1061}
5424bc55
TRC
1062
1063/* Helpers for fetching objects (loose) */
1064static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
1065 void *data)
1066{
1067 unsigned char expn[4096];
1068 size_t size = eltsize * nmemb;
1069 int posn = 0;
1070 struct http_object_request *freq =
1071 (struct http_object_request *)data;
1072 do {
1073 ssize_t retval = xwrite(freq->localfile,
1074 (char *) ptr + posn, size - posn);
1075 if (retval < 0)
1076 return posn;
1077 posn += retval;
1078 } while (posn < size);
1079
1080 freq->stream.avail_in = size;
1081 freq->stream.next_in = ptr;
1082 do {
1083 freq->stream.next_out = expn;
1084 freq->stream.avail_out = sizeof(expn);
1085 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1086 git_SHA1_Update(&freq->c, expn,
1087 sizeof(expn) - freq->stream.avail_out);
1088 } while (freq->stream.avail_in && freq->zret == Z_OK);
1089 data_received++;
1090 return size;
1091}
1092
1093struct http_object_request *new_http_object_request(const char *base_url,
1094 unsigned char *sha1)
1095{
1096 char *hex = sha1_to_hex(sha1);
1097 char *filename;
1098 char prevfile[PATH_MAX];
5424bc55
TRC
1099 int prevlocal;
1100 unsigned char prev_buf[PREV_BUF_SIZE];
1101 ssize_t prev_read = 0;
1102 long prev_posn = 0;
1103 char range[RANGE_HEADER_SIZE];
1104 struct curl_slist *range_header = NULL;
1105 struct http_object_request *freq;
1106
1107 freq = xmalloc(sizeof(*freq));
1108 hashcpy(freq->sha1, sha1);
1109 freq->localfile = -1;
1110
1111 filename = sha1_file_name(sha1);
1112 snprintf(freq->filename, sizeof(freq->filename), "%s", filename);
1113 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1114 "%s.temp", filename);
1115
1116 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1117 unlink_or_warn(prevfile);
1118 rename(freq->tmpfile, prevfile);
1119 unlink_or_warn(freq->tmpfile);
1120
1121 if (freq->localfile != -1)
1122 error("fd leakage in start: %d", freq->localfile);
1123 freq->localfile = open(freq->tmpfile,
1124 O_WRONLY | O_CREAT | O_EXCL, 0666);
1125 /*
1126 * This could have failed due to the "lazy directory creation";
1127 * try to mkdir the last path component.
1128 */
1129 if (freq->localfile < 0 && errno == ENOENT) {
1130 char *dir = strrchr(freq->tmpfile, '/');
1131 if (dir) {
1132 *dir = 0;
1133 mkdir(freq->tmpfile, 0777);
1134 *dir = '/';
1135 }
1136 freq->localfile = open(freq->tmpfile,
1137 O_WRONLY | O_CREAT | O_EXCL, 0666);
1138 }
1139
1140 if (freq->localfile < 0) {
1141 error("Couldn't create temporary file %s for %s: %s",
1142 freq->tmpfile, freq->filename, strerror(errno));
1143 goto abort;
1144 }
1145
1146 memset(&freq->stream, 0, sizeof(freq->stream));
1147
1148 git_inflate_init(&freq->stream);
1149
1150 git_SHA1_Init(&freq->c);
1151
bb99190e 1152 freq->url = get_remote_object_url(base_url, hex, 0);
5424bc55
TRC
1153
1154 /*
1155 * If a previous temp file is present, process what was already
1156 * fetched.
1157 */
1158 prevlocal = open(prevfile, O_RDONLY);
1159 if (prevlocal != -1) {
1160 do {
1161 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1162 if (prev_read>0) {
1163 if (fwrite_sha1_file(prev_buf,
1164 1,
1165 prev_read,
1166 freq) == prev_read) {
1167 prev_posn += prev_read;
1168 } else {
1169 prev_read = -1;
1170 }
1171 }
1172 } while (prev_read > 0);
1173 close(prevlocal);
1174 }
1175 unlink_or_warn(prevfile);
1176
1177 /*
1178 * Reset inflate/SHA1 if there was an error reading the previous temp
1179 * file; also rewind to the beginning of the local file.
1180 */
1181 if (prev_read == -1) {
1182 memset(&freq->stream, 0, sizeof(freq->stream));
1183 git_inflate_init(&freq->stream);
1184 git_SHA1_Init(&freq->c);
1185 if (prev_posn>0) {
1186 prev_posn = 0;
1187 lseek(freq->localfile, 0, SEEK_SET);
0c4f21e4
JL
1188 if (ftruncate(freq->localfile, 0) < 0) {
1189 error("Couldn't truncate temporary file %s for %s: %s",
1190 freq->tmpfile, freq->filename, strerror(errno));
1191 goto abort;
1192 }
5424bc55
TRC
1193 }
1194 }
1195
1196 freq->slot = get_active_slot();
1197
1198 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1199 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1200 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
bb99190e 1201 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
5424bc55
TRC
1202 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1203
1204 /*
1205 * If we have successfully processed data from a previous fetch
1206 * attempt, only fetch the data we don't already have.
1207 */
1208 if (prev_posn>0) {
1209 if (http_is_verbose)
1210 fprintf(stderr,
1211 "Resuming fetch of object %s at byte %ld\n",
1212 hex, prev_posn);
1213 sprintf(range, "Range: bytes=%ld-", prev_posn);
1214 range_header = curl_slist_append(range_header, range);
1215 curl_easy_setopt(freq->slot->curl,
1216 CURLOPT_HTTPHEADER, range_header);
1217 }
1218
1219 return freq;
1220
5424bc55
TRC
1221abort:
1222 free(filename);
bb99190e 1223 free(freq->url);
5424bc55
TRC
1224 free(freq);
1225 return NULL;
1226}
1227
1228void process_http_object_request(struct http_object_request *freq)
1229{
1230 if (freq->slot == NULL)
1231 return;
1232 freq->curl_result = freq->slot->curl_result;
1233 freq->http_code = freq->slot->http_code;
1234 freq->slot = NULL;
1235}
1236
1237int finish_http_object_request(struct http_object_request *freq)
1238{
1239 struct stat st;
1240
1241 close(freq->localfile);
1242 freq->localfile = -1;
1243
1244 process_http_object_request(freq);
1245
1246 if (freq->http_code == 416) {
1247 fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
1248 } else if (freq->curl_result != CURLE_OK) {
1249 if (stat(freq->tmpfile, &st) == 0)
1250 if (st.st_size == 0)
1251 unlink_or_warn(freq->tmpfile);
1252 return -1;
1253 }
1254
1255 git_inflate_end(&freq->stream);
1256 git_SHA1_Final(freq->real_sha1, &freq->c);
1257 if (freq->zret != Z_STREAM_END) {
1258 unlink_or_warn(freq->tmpfile);
1259 return -1;
1260 }
1261 if (hashcmp(freq->sha1, freq->real_sha1)) {
1262 unlink_or_warn(freq->tmpfile);
1263 return -1;
1264 }
1265 freq->rename =
1266 move_temp_to_file(freq->tmpfile, freq->filename);
1267
1268 return freq->rename;
1269}
1270
1271void abort_http_object_request(struct http_object_request *freq)
1272{
1273 unlink_or_warn(freq->tmpfile);
1274
1275 release_http_object_request(freq);
1276}
1277
1278void release_http_object_request(struct http_object_request *freq)
1279{
1280 if (freq->localfile != -1) {
1281 close(freq->localfile);
1282 freq->localfile = -1;
1283 }
1284 if (freq->url != NULL) {
1285 free(freq->url);
1286 freq->url = NULL;
1287 }
4b9fa0e3
TRC
1288 if (freq->slot != NULL) {
1289 freq->slot->callback_func = NULL;
1290 freq->slot->callback_data = NULL;
1291 release_active_slot(freq->slot);
1292 freq->slot = NULL;
1293 }
5424bc55 1294}