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