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